Skip to content

Instantly share code, notes, and snippets.

@crazybugliu
Last active June 3, 2016 13:58
Show Gist options
  • Save crazybugliu/93df5ce14c564a8fa339c7fffd2ccedb to your computer and use it in GitHub Desktop.
Save crazybugliu/93df5ce14c564a8fa339c7fffd2ccedb to your computer and use it in GitHub Desktop.
Js-spark-md5 的一种使用方式 可以配合drop-zone使用
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();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment