1.下载MD5依赖
npm install crypto-js
2.在utils文件夹中新增文件md5方法文件,文件名自定义(fileMd5Sum.js)
import CryptoJs from 'crypto-js'
export default {// md5值计算fileMd5Sum(file) {let CryptoJS = require("crypto-js");return new Promise(resolve => {const fileReader = new FileReader();fileReader.onloadend = ev => {resolve(CryptoJS.MD5(CryptoJS.enc.Latin1.parse(ev.target.result)).toString(CryptoJS.enc.Hex));};fileReader.readAsBinaryString(file);});}
}
3.定义全局变量在main.js中引入
//文件md5计算方法
import fileMd5Sum from '@/utils/fileMd5Sum.js';
Vue.prototype.fileMd5Sum = fileMd5Sum;
4.使用
// files是上传的文件
this.fileMd5Sum.fileMd5Sum(files).then((res)-=>{console.log(res) // res就是加密后生成的md5
})
5.这是一个切片上传的例子
// dom
<el-upload :show-file-list="false" accept=".doc,.docx" ref="uploads" :limit="1" action:http-request="putinMirror3" :auto-upload="true"><el-button size="small" type="primary">数据上传</el-button><el-input v-model="addform.dataTestnMame" autocomplete="off" style="width:350px;margin-left: 20px;" disabledv-if="first4"></el-input><el-progress :text-inside="true" :stroke-width="26" :percentage="percentage4" v-if="!first4"style="position:absolute;left:150px;width:300px;top:0px"></el-progress></el-upload>// 切片上传putinMirror3(file) {let param = {fileName: file.file.name}firstFileUp(param).then(response => {var uploadId = response.data.uploadId// 每个文件切片大小定为5MBvar sliceSize = 50 * 1024 * 1024;//文件大小限制为最大10个G,可根据需求修改var filesizes = 100 * 1024 * 1024 * 1024;let that = this;const blob = file.file;const fileSize = blob.size;// 文件大小// this.fileNmae.push(blob.name)const fileName = blob.name;// 文件名//计算文件切片总数var totalSlice = 0;if (fileSize >= sliceSize) {totalSlice = Math.ceil(fileSize / sliceSize)} else {totalSlice = 1}var num = 0var list = []var guid = Date.parse(new Date())if (fileSize <= filesizes) {// 循环上传for (let i = 0; i < totalSlice; i++) {let start = i * sliceSize;let chunk = blob.slice(start, Math.min(fileSize, start + sliceSize));let files = new File([chunk], fileName)let partSize = files.sizethis.fileMd5Sum.fileMd5Sum(files).then(res => {var formData = new FormData();formData.append("uploadId", uploadId);formData.append("file", files);formData.append("partSize", partSize);formData.append("partNumber", i + 1);formData.append("md5Digest", res);let instance = axios.create({baseURL: 'baseUrl',data: formData,headers: { 'Content-Type': 'multipart/form-data', 'Authorization': "Bearer " + getAccessToken() }})this.first4 = falseinstance.post(`${this.uploadFileUrl}`, formData).then((res) => {if (res.data.code == 0) {list.push(res.data.data)this.percentage4 = Number(((list.length / totalSlice) * 100).toFixed(2))if (list.length == totalSlice) {let param = {uploadId: uploadId,partTags: list}secendFileUp(param).then(response => {this.fileList4.push(response.data)this.percentage4 = 100});}} else {that.$message({message: res.msg,type: 'error'});}})});}} else {that.$message({message: '文件大小超出10G',type: 'error'});}});},