HTML5 File API - slicing or not?

后端 未结 2 1402
梦谈多话
梦谈多话 2021-02-06 09:14

There are some nice examples about file uploading at HTML5 Rocks but there are something that isn\'t clear enough for me.

As far as i see, the example code about file sl

相关标签:
2条回答
  • 2021-02-06 09:55

    This is the way to slice the file to pass as blobs:

    function readBlob() {
        var files = document.getElementById('files').files;
        var file = files[0];
        var ONEMEGABYTE = 1048576;
        var start = 0;
        var stop = ONEMEGABYTE;
    
        var remainder = file.size % ONEMEGABYTE;
        var blkcount = Math.floor(file.size / ONEMEGABYTE);
        if (remainder != 0) blkcount = blkcount + 1;
    
        for (var i = 0; i < blkcount; i++) {
    
            var reader = new FileReader();
            if (i == (blkcount - 1) && remainder != 0) {
                stop = start + remainder;
            }
            if (i == blkcount) {
                stop = start;
            }
    
            //Slicing the file 
            var blob = file.webkitSlice(start, stop);
            reader.readAsBinaryString(blob);
            start = stop;
            stop = stop + ONEMEGABYTE;
    
        } //End of loop
    
    } //End of readblob
    
    0 讨论(0)
  • 2021-02-06 10:12

    Both Chrome and FF support File.slice() but it has been prefixed as File.webkitSlice() File.mozSlice() when its semantics changed some time ago. There's another example of using it here to read part of a .zip file. The new semantics are:

    Blob.webkitSlice( 
      in long long start, 
      in long long end, 
      in DOMString contentType 
    ); 
    

    Are you safe without slicing it? Sure, but remember you're reading the file into memory. The HTML5Rocks tutorial offers chunking the upload as a potential performance improvement. With some decent server logic, you could also do things like recovering from a failed upload more easily. The user wouldn't have to re-try an entire 500MB file if it failed at 99% :)

    0 讨论(0)
提交回复
热议问题