VUE项目中使用到<el-upload>
上传,想要独立显示上传进度条
1、HTML代码
<template>
<el-upload
:disabled="isUploading"
ref="upload"
:limit="1"
accept=".bin"
:headers="headers"
:action="url"
:show-file-list="false"
:http-request="uploadSectionFile"
class="uploadStyle"
>
<el-button
:loading="isUploading"
:disabled="isUploading"
slot="trigger"
type="primary"
plain
size="small"
icon="el-icon-upload2"
>{
{ isUploading ? "文件上传中" : '上传')}}</el-button
>
<el-progress v-if="isShow" :percentage="uploadProgress" :text-inside="false" :color="customColors" :stroke-width="4" />
</el-upload>
</template>
import {
getToken } from "@/utils/auth";
import {
importPackage } from "@/api/soft";
export default {
name: "CommonUpload",
data() {
return {
isShow: false,
isUploading: false,
headers: {
Authorization: "Bearer " + getToken() },
url: process.env.VUE_APP_BASE_API + "/xxx",
loading: false,
uploadProgress: 0,
customColors: [
{
color: 'rgba(223,228,237,0.10)', percentage: 0 },
{
color: '#00adc9', percentage: 100 }
],
};
},
}
2、上传接口 增加 config
参数,并用...config
将该属性加入到请求中;
export function importPackage(data, config) {
return request({
url: '/xxx',
method: 'post',
data: data,
timeout: 120 * 1000,
headers: {
'Content-Type': 'multipart/form-data'
},
...config
})
}
3、上传实现
uploadSectionFile(data) {
this.uploadProgress = 0;
const file = data.file;
const isLt2M = file.size / 1024 / 1024 < 500;
if (!isLt2M) {
this.$message.error("文件大小不得超过500MB");
return;
}
this.$refs.upload.clearFiles();
this.isShow = true;
this.submitForm(file);
},
submitForm: function (file) {
var that = this;
that.isUploading = true;
let formData = new FormData();
formData.append("file", file);
const config = {
onUploadProgress: progressEvent => {
if (progressEvent.lengthComputable) {
that.uploadProgress = Math.round((progressEvent.loaded / progressEvent.total) * 100);
}
}
};
importPackage(formData, config).then((response) => {
that.isUploading = false;
that.$modal.msgSuccess("上传成功");
setTimeout(() => {
that.isShow = false;
}, 500)
})
.catch(() => {
that.isUploading = false;
setTimeout(() => {
that.isShow = false;
}, 500)
});
}