Skip to content Skip to sidebar Skip to footer

HTML5 File API - Slicing Or Not?

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 slicing is get

Solution 1:

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% :)


Solution 2:

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

Post a Comment for "HTML5 File API - Slicing Or Not?"