网上搜到的文章都乱七八糟的,参照官方例子稍微改了改
/**
* 分片获取md5值
* @param {*} file 文件对象
* @param {*} chunkSize 分片大小
* @param {*} progressCallback 进度修改回调
* @returns
*/
function md5WithChunk(file, chunkSize, progressCallback = console.log) {
return new Promise((resolve, reject) => {
const blobSlice =
File.prototype.slice ||
File.prototype.mozSlice ||
File.prototype.webkitSlice
let chunks = Math.ceil(file.size / chunkSize)
let currentChunk = 0
let spark = new SparkMD5.ArrayBuffer()
let fileReader = new FileReader()
fileReader.onerror = reject
fileReader.onload = (e) => {
processCallback(currentChunk / chunks)
spark.append(e.target.result)
currentChunk++
if (currentChunk < chunks) {
loadNext()
} else {
resolve(spark.end())
}
}
function loadNext() {
let start = currentChunk * chunkSize
let end = start + chunkSize >= file.size ? file.size : start + chunkSize
fileReader.readAsArrayBuffer(blobSlice.call(file, start, end))
}
loadNext()
})
}
使用
<input id="file" type="file" onchange="showMd5(this.files[0])">
<script>
async function showMd5(file) {
let md5 = await md5WithChunk(file,2*1024**2) //2MB
console.log(md5);
}
<script>
效果(控制台)
0
0.006896551724137931
0.013793103448275862
0.020689655172413793
....
0.9862068965517241
0.993103448275862
9f120ab831064012ff641ca83e918057