一、npm 安装 md5
npm i spark-md5 --save
import SparkMD5 from "spark-md5";
export function getFileMd5(file, chunkCount, chunkSize) {
return new Promise((resolve, reject) => {
let blobSlice = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice;
let chunks = chunkCount;
let currentChunk = 0;
let spark = new SparkMD5.ArrayBuffer();
let fileReader = new FileReader();
fileReader.onload = function (e) {
spark.append(e.target.result);
currentChunk++;
if (currentChunk < chunks) {
loadNext();
} else {
let md5 = spark.end();
resolve(md5);
}
};
fileReader.onerror = function (e) {
reject(e);
};
function loadNext() {
let start = currentChunk * chunkSize;
let end = start + chunkSize;
if (end > file.size) {
end = file.size;
}
fileReader.readAsArrayBuffer(blobSlice.call(file, start, end));
}
loadNext();
});
}
二、设置参数&分片上传代码
const chunkSize = 10 * 1024 * 1024;
function getBase64(img, callback) {
const reader = new FileReader();
reader.addEventListener("load", () => callback(reader.result));
reader.readAsDataURL(img);
}
beforeUpload(file) {
let _continue = true;
let { name, size } = file;
name = toLower(name);
const fileSize = size / 1024 / 1024
if (fileSize > 100) {
this.sparkMd5 = true
}else{
this.sparkMd5 = false
}
},
async localFiles(File) {
let file = File.file;
let fileList = cloneDeep(this.localFileList),
maxLength = this.maxLength;
getBase64(file, url => {
file.url = url;
file.thumUrl = url;
});
if (this.sparkMd5) {
let num = 0
this.sparkMd5File.push(file)
this.sparkModalVisible = true
const fileSize = file.size
this.currentFileSize = fileSize
const chunkCount = Math.ceil(fileSize / chunkSize)
const fileMd5 = await getFileMd5(file, chunkCount,chunkSize);
for (var i = 0; i < chunkCount; i++) {
let start = i * chunkSize
let end = (i + 1) * chunkSize
let _chunkFile = file.slice(start, end)
let fileName = new Date().getTime() + "_" + file.name;
let form = new FormData()
form.append('file', _chunkFile)
form.append('type',file.type)
form.append('chunkNumber', i+1)
form.append('chunkSize', chunkSize)
form.append('currentChunkSize', _chunkFile.size,)
form.append('identifier', fileMd5)
form.append('filename', i + "_" + fileName)
form.append('totalChunks', chunkCount)
form.append('totalSize', fileSize)
try {
await upLoadChunk(form)
num += (100 / chunkCount).toExponential(2) - 0
this.progress = num.toExponential(2) - 0
} catch (error) {
this.sparkModalVisible = false
this.$message.error("网络错误");
return
}
}
await this.composeFile(fileMd5, file.name, chunkCount)
}
},
三、合并文件
composeFile(fileMd5, fileName, count) {
this.spinning = true
var data = {
"businessType": this.businessType,
"totalSize": this.currentFileSize,
"identifier": fileMd5,
"fileName": fileName,
"totalChunks": count
}
mergeChunk(data).then(res=>{
this.uploadedIdsTemp.push(res.id)
this.$message.success("合并成功");
this.sparkModalVisible = false
this.spinning = false
this.progress = 0
})
},