安装spark-md5
npm install spark-md5
//引入spark-md5
import SparkMD5 from 'spark-md5'
//方法
calculate:计算文件的MD5值,或者计算大文件的文件分片的MD5值
append:追加数据
init:重置MD5值
end:使用字节数组作为结束符计算MD5值
import SparkMD5 from 'spark-md5'
const DEFAULT_SIZE = 10 * 1024 * 1024;
const blobSlice = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice;
const md5 = (file, chunkSize = DEFAULT_SIZE) => {
return new Promise((resolve, reject) => {
const startTmie = new Date().getTime();
let chunks = Math.ceil(file.size / chunkSize);
let currentChunk = 0;
let spark = new SparkMD5.ArrayBuffer();
let fileReader = new FileReader(); //读取文件
fileReader.onload = function (e) {
spark.append(e.target.result); //追加数组缓冲区
currentChunk++;
if (currentChunk < chunks) {
loadNext();
} else {
console.log('文件md5计算结束,总耗时:', (new Date().getTime() - startTmie) / 1000, 's')
resolve(spark.end()); //完成md5的计算,返回十六进制结果。
}
};
fileReader.onerror = function (e) {
reject(e);
};
function loadNext() {
console.log('当前part number:', currentChunk, '总块数:', chunks);
let start = currentChunk * chunkSize;
let end = end > file.size ? file.size : start + chunkSize;
fileReader.readAsArrayBuffer(blobSlice.call(file, start, end));
}
loadNext();
});
}
export default md5