js获取md5值使用的spark-md5插件,相比browser-md5-file会快很多
import SparkMD5 from 'spark-md5';
const getMd5 = function (file) {
return new Promise((resolve, reject) => {
var blobSlice = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice,
// file = file,
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) {
// 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
resolve(spark.end())
}
};
fileReader.onerror = function () {
reject('计算失败')
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();
})
}
//使用1
getMd5(file).then(res => this.md5 = res)
//使用2
//可以在elementui等上传组件的beforeupload里执行
async function asdf(file){
this.md5 = await getMd5(file)
}