计算文件hash,使用到了模块 js-sha1
该模块文档:GitHub - emn178/js-sha1: A simple SHA1 hash function for JavaScript supports UTF-8 encoding.
主要思路就是通过内置方法 slice 分块按顺序计算hash值
import sha1 from 'js-sha1'
export async function ContentHash(file, progress) {
return new Promise((resolve, reject) => {
const chunkSize = 50 * 1024 * 1024
let promise = Promise.resolve()
for (let index = 0; index < file.size; index += chunkSize) {
promise = promise.then(() => hashBlob(file.slice(index, index + chunkSize)))
}
let count = 0
const hash = sha1.create()
function hashBlob(blob) {
return new Promise((resolve, reject) => {
const reader = new FileReader()
reader.onload = ({target}) => {
hash.update(target.result)
count += 1
resolve()
}
reader.onerror = function (event) {
reject(event)
}
reader.onprogress = function (event) {
if (event) {
progress = Math.ceil((event.loaded + count * chunkSize) * 100 / progress.file_size)
}
}
reader.readAsArrayBuffer(blob)
})
}
promise.then(async () => {
const conHash = hash.hex().toUpperCase()
resolve({conHash})
}).catch(() => {
reject()
})
})
}