crypto-js+vue+el-upload 计算文件hash(sha256)
下载crypto-js
npm i crypto-js
如何使用
index.vue
<template>
<el-upload ref="upload" drag action :http-request="uploadCrt"></el-upload>
</template>
<script>
import CryptoJS from 'crypto-js'
export default {
...
methods: {
uploadCrt(param) {
var contractFile = param.file;
var reader = new FileReader(), self = this;;
var blobSlice = File.prototype.mozSlice || File.prototype.webkitSlice || File.prototype.slice;
var chunkSize = 6 * 1024 * 1024;
var chunks = Math.ceil(contractFile.size / chunkSize);
var currentChunk = 0;
var hasher = CryptoJS.algo.SHA256.create();
var start = currentChunk * chunkSize;
var end = start + chunkSize >= contractFile.size ? contractFile.size : start + chunkSize;
reader.readAsArrayBuffer(blobSlice.call(contractFile, start, end));
reader.onload = function (evt) {
var fileStr = evt.target.result;
var tmpWordArray = self.arrayBufferToWordArray(fileStr);
hasher.update(tmpWordArray);
currentChunk += 1;
fileStr = null;
tmpWordArray = null;
if (currentChunk < chunks) {
var start = currentChunk * chunkSize;
var end = start + chunkSize >= contractFile.size ? contractFile.size : start + chunkSize;
reader.readAsArrayBuffer(blobSlice.call(contractFile, start, end));
}
}
reader.onloadend = function () {
contractFile = null;
var hash = hasher.finalize();
hash.toString();//计算结果
hasher = null;
blobSlice = null;
reader = null;
hash = null;
}
},
arrayBufferToWordArray(ab) {
var i8a = new Uint8Array(ab);
var a = [];
for (var 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);
},
}
}
</script>
<p style="color: #FFB6C1">一招毙命 , 打完收工,✿✿ヽ(°▽°)ノ✿</p>
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。