计算文件hash值(SHA1)
参考自https://www.jianshu.com/p/59a06a08efac
参考自
获取到文件对象后
//导入
import CryptoJS from "crypto-js";
//上传文件触发事件
uploadCrt(param) {
let contractFile = param.file;
let reader = new FileReader(),
self = this;
let blobSlice =
File.prototype.mozSlice ||
File.prototype.webkitSlice ||
File.prototype.slice;
let chunkSize = 10 * 1024 * 1024;
let chunks = Math.ceil(contractFile.size / chunkSize);
let currentChunk = 0;
let hasher = CryptoJS.algo.SHA1.create();
console.log(`CryptoJS.algo.SHA1.create`, CryptoJS.algo.SHA1.create);
let start = currentChunk * chunkSize;
let end =
start + chunkSize >= contractFile.size
? contractFile.size
: start + chunkSize;
reader.readAsArrayBuffer(blobSlice.call(contractFile, start, end));
reader.onload = function(evt) {
let fileStr = evt.target.result;
let tmpWordArray = self.arrayBufferToWordArray(fileStr);
hasher.update(tmpWordArray);
currentChunk += 1;
fileStr = null;
tmpWordArray = null;
if (currentChunk < chunks) {
let start = currentChunk * chunkSize;
let end =
start + chunkSize >= contractFile.size
? contractFile.size
: start + chunkSize;
reader.readAsArrayBuffer(blobSlice.call(contractFile, start, end));
}
};
reader.onloadend = function() {
contractFile = null;
let hash = hasher.finalize();
hash.toString(); //计算结果
console.log(
`hash.toString().length`,
hash.toString() === "d6de0ccc33b360d5e04125b8d9e0f38962d10d08"
);
// 可以百度或命令行‘在线计算hash文件工具,然后将计算后的值与hash.tostring()的 值进行对比 SHA1生成的是40位的字符串’
hasher = null;
blobSlice = null;
reader = null;
hash = null;
};
},
arrayBufferToWordArray(ab) {
let i8a = new Uint8Array(ab);
let a = [];
for (let i = 0; i < i8a.length; i += 4) {
a.push(
(i8a[i] << 24) | (i8a[i + 1] << 16) | (i8a[i + 2] << 8) | i8a[i + 3]
);
}
return CryptoJS.lib.WordArray.create(a, i8a.length);
},
//导入
import CryptoJS from "crypto-js";
getHash(file){
let reader = new FileReader();
// 读取文件 file
reader.readAsArrayBuffer(file);
reader.onload = function () {
var wordArray = CryptoJS.lib.WordArray.create(reader.result);
var hash = CryptoJS.SHA1(wordArray).toString(); // 计算其他加密算法,SHA1改为MD5、SHA256即可
console.log('hash:', hash)
};
}
本文非原创,在作者的基础上根据自己需求做了修改
以上。