首先使用element的上传文件的组件
安装依赖crypto-js
<el-upload
class="upload-demo"
drag
:http-request="uploadCrt"
action=""
:limit='1'
:file-list="fileList"
:on-exceed='_change'
>
<i class="el-icon-upload"></i>
<div class="el-upload__text">
将文件拖到此处,或<em>点击上传</em>
</div>
</el-upload>
然后写方法
uploadCrt(param) {
let that = this;
var contractFile = param.file;
// console.log(contractFile)
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(); //计算结果
that.filehash = hash.toString();
console.log(that.filehash)
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);
},
标红的就是计算出来的sha256的值