Skip to content

Instantly share code, notes, and snippets.

@marlocorridor
Created September 3, 2015 04:39
Show Gist options
  • Save marlocorridor/3e6484ae5a646bd7c625 to your computer and use it in GitHub Desktop.
Save marlocorridor/3e6484ae5a646bd7c625 to your computer and use it in GitHub Desktop.
Deferred Implmentation of spark md5 js library.
function getFileMd5 ( file ) {
var dfd = jQuery.Deferred();
/**
* reference:
* https://github.com/satazor/SparkMD5
*/
var blobSlice = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice,
chunkSize = 2097152, // Read in chunks of 2MB
chunks = Math.ceil(file.size / chunkSize),
currentChunk = 0,
spark = new SparkMD5.ArrayBuffer(),
fileReader = new FileReader();
fileReader.onload = function (e) {
dfd.notify('read chunk # ' + (currentChunk + 1) + ' of ' + chunks);
spark.append(e.target.result); // Append array buffer
currentChunk++;
if (currentChunk < chunks) {
loadNext();
} else {
dfd.resolve( spark.end() );
}
};
fileReader.onerror = function () {
dfd.reject('oops, something went wrong.');
};
var loadNext = function() {
var start = currentChunk * chunkSize,
end = ((start + chunkSize) >= file.size) ? file.size : start + chunkSize;
fileReader.readAsArrayBuffer(blobSlice.call(file, start, end));
};
loadNext();
return dfd.promise();
}
@marlocorridor
Copy link
Author

@meyer59, sorry for the late reply.

first, you should include the dependencies/libraries. SparkMD5 and jQuery

the getFileMd5 method's file parameter accepts FIle class.
https://developer.mozilla.org/en-US/docs/Web/API/File

File objects are generally retrieved from a FileList object returned as a result of a user selecting files using the element...

I used this with DropzoneJs. This is my implementation.

    dropzone_uploader.on('addedfile', function ( file ) {
        getFileMd5( file ).done( function ( result, file ) {
            //your code here
        });
    });

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment