Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read huge files in browser using FileReader (web api)

I'm trying to read the first byte of the selected file.

But when I select a large file (>100Mb) I get an error: "NotReadableError".

See the code below. Is "array buffer" really a buffer or it just loads the whole stuff into the memory and I MUST use file#slice?

function readFile(file) {
  var reader = new FileReader();
  
  reader.onload = function() {
    var buffer = reader.result;
    var view = new Int8Array(buffer);
    try {
      view.forEach(function(v, index, array) {
        console.log(v);
        alert("ok - " + v);
        throw "BreakException";
      })
    } catch (e) {
      if (e!=="BreakException") throw e;
    }
  }
  
  reader.onerror = function() {
    alert("error");
    console.log(reader.error);
  }
  
  reader.readAsArrayBuffer(file);
}

var fileField = document.getElementById("file");

fileField.onchange = function(e) {
  var file = e.target.files[0];
  readFile(file);
}
<form>
  <input id="file" type="file"/>
</form>
like image 852
Artsiom Avatar asked Dec 05 '15 18:12

Artsiom


1 Answers

An ArrayBuffer is really a buffer, an in-memory buffer. That's how buffers work. Your code tries to load the whole file into memory. To access specific ranges of a file without loading the whole into memory, you must use Blob.slice (Files implement all the methods of Blobs) as you suspected.

like image 64
Tamas Hegedus Avatar answered Sep 27 '22 00:09

Tamas Hegedus