
js-spark-md5是做什么的? js-spark-md5是号称全宇宙最快的前端类包,可以无需上传文件就快速获取本地文件md5.
可能你觉得这没什么,但是,当你做一个文件系统时候,就有这需求,用这个简单的前端类库就能实现你“秒传”的功能!这里我解释下,每个文件的md5值都是唯一的,这也是很多下载网站,会告诉你原文件的md5是多少,然后下载完毕让你自行去对比下,如果一致,就说明文件是完整的。
好了,正因为每个文件的md5是一样的,那么,我们在做文件上传的时候,就只要在前端先获取要上传的文件md5,并把文件md5传到服务器,对比之前文件的md5,如果存在相同的md5,我们只要把文件的名字传到服务器关联之前的文件即可,并不需要再次去上传相同的文件,再去耗费存储资源、上传的时间、网络带宽。
Install
npm install --save spark-md5var hexHash = SparkMD5.hash('Hi there'); // hex hash
var rawHash = SparkMD5.hash('Hi there', true); // OR raw hash (binary string)
var spark = new SparkMD5();
spark.append('Hi');
spark.append(' there');
var hexHash = spark.end(); // hex hash
var rawHash = spark.end(true); // OR raw hash (binary string)
NOTE: If you test the code bellow using the file:// protocol in chrome you must start the browser with -allow-file-access-from-files argument. Please see:
http://code.google.com/p/chromium/issues/detail?id=60889document.getElementById('file').addEventListener('change', function () {
var blobSlice = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice,
file = this.files[],
chunkSize = 2097152, // Read in chunks of 2MB
chunks = Math.ceil(file.size / chunkSize),
currentChunk = ,
spark = new SparkMD5.ArrayBuffer(),
fileReader = new FileReader();
fileReader.onload = function (e) {
console.log('read chunk nr', currentChunk + 1, 'of', chunks);
spark.append(e.target.result); // Append array buffer
currentChunk++;
if (currentChunk < chunks) {
loadNext();
} else {
console.log('finished loading');
console.info('computed hash', spark.end()); // Compute hash
}
};
fileReader.onerror = function () {
console.warn('oops, something went wrong.');
};
function loadNext() {
var start = currentChunk * chunkSize,
end = ((start + chunkSize) >= file.size) ? file.size : start + chunkSize;
fileReader.readAsArrayBuffer(blobSlice.call(file, start, end));
}
loadNext();
});
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/31509949/viewspace-3166224/ ,如需转载,请注明出处,否则将追究法律责任。