Crypto-js +vue+el-upload Compute file hash(sha256)

Download the crypto – js

npm i crypto-js
Copy the code

How to use

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>Copy the code

A recruit dead, after finishing work, remember (°▽°) Blue ✿