javascript - Read huge files in browser using FileReader (web api) - Stack Overflow

admin2025-04-19  0

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>

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>

Share Improve this question asked Dec 5, 2015 at 18:13 ArtsiomArtsiom 993 silver badges11 bronze badges 1
  • Buffer != stream. If the file is 100MB, the buffer will probably be 100MB, and mem usage will be 200MB. – Rudie Commented Dec 5, 2015 at 18:17
Add a ment  | 

1 Answer 1

Reset to default 6

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.

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1745021629a280415.html

最新回复(0)