首先我们需要先把上传文件的file获取出来,就好像这样。
下一步就把file传入我们的分片事件上做处理,ok话不多说,直接上代码,这里的分片没有做错误的提示的,可以自行调整。(一般来说是可以直接使用的,最多就是修改一下后端需要你改传回去的字段)
// 在data里声明好对象
uploadFileData: {
LENGTH: 1024 * 1024 * 2,
start: 0,
end: 0,
blob: "",
blob_num: 0,
total_blob_num: 0,
uuid: "",
original_name: "",
size: 0,
mime: ""
},
fileSlice(file) {
const LENGTH = 1024 * 1024 * 2;
const startNum = this.uploadFileData.start
? this.uploadFileData.start
: 0;
this.uploadFileData = {
LENGTH,
start: 0,
end: startNum + LENGTH,
blob: "",
blob_num: 0,
total_blob_num: Math.ceil(file.size / LENGTH),
uuid: this.generateUUID(),
original_name: file.name,
size: file.size,
mime: file.type
};
for (let i = 0; i < this.uploadFileData.total_blob_num; i++) {
this.uploadFileData.blob =
this.uploadFileData.total_blob_num > 1 ? this.cutFile(file) : file;
this.sendFile(file);
}
},
async sendFile() {
let that = this;
this.uploadFileData.blob_num++;
// 这里传的类型不一定是这个,可以根据自己的需求进行修改
const form_data = new FormData();
form_data.append("file", this.uploadFileData.blob);
form_data.append("required_id", this.uploadFileData.uuid);
form_data.append("blob_num", Number(this.uploadFileData.blob_num));
form_data.append(
"total_blob_num",
Number(this.uploadFileData.total_blob_num)
);
form_data.append("size", Number(this.uploadFileData.size));
form_data.append("mime", this.uploadFileData.mime);
form_data.append("original_name", this.uploadFileData.original_name);
form_data.append("type", this.uploadFileData.mime);
await axios({
method: "POST",
url: baseURL + "/admin/files/slice-upload",
headers: {
"Content-Type": "multipart/form-data",
Authorization: `Bearer ${this.token}`
},
data: form_data
})
.then(res => {
that.uploadIndex++;
// 这里判断是文件小于2m的情况下是不需要通知文件合成的
// 所以我这里是上传完就直接赋值出去使用了
// 这里需要跟后台沟通,看后台怎么处理
// 有些情况是直接在最后一个分片访问接口成功后返回你需要的图片或者视频地址
if (res.status && res.status === 200) {
this.addVideo(res.data.url);
} else {
if (that.uploadIndex === that.uploadFileData.total_blob_num) {
that.handlemerge();
}
}
})
.catch(error => {
console.log(error.response);
});
},
// 图片合成
async handlemerge() {
let params = {
required_id: this.uploadFileData.uuid,
original_name: this.uploadFileData.original_name
};
let res = await this.$store.dispatch("postFilesSliceMerge", params);
this.addVideo(res.url);
},
// 生成唯一字段,用来后台判断是哪一张图片的
generateUUID() {
/* eslint-disable no-bitwise, no-mixed-operators */
let d = new Date().getTime();
if (window.performance && typeof window.performance.now === "function") {
d += performance.now();
}
const uuid = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(
/[xy]/g,
c => {
const r = (d + Math.random() * 16) % 16 | 0;
d = Math.floor(d / 16);
return (c === "x" ? r : (r & 0x3) | 0x8).toString(16);
}
);
return uuid;
},
// 切割文件
cutFile(file) {
const file_blob = file.slice(
this.uploadFileData.start,
this.uploadFileData.end
);
this.uploadFileData.start = this.uploadFileData.end;
this.uploadFileData.end =
this.uploadFileData.start + this.uploadFileData.LENGTH;
return file_blob;
},