使用Upload+Progress實現(xiàn)文件上傳進度條實時更新功能沮焕,需要借助http-request屬性叉袍。具體使用方法如下:
<el-upload
action="#"
:file-list="fileList"
:on-change="changeData"
:http-request="handleRequest"
:before-upload="beforeUpload">
<el-button class="btn upload-btn">上傳附件</el-button>
<div slot="tip" class="el-upload__tip">上傳文件大小不超過50M</div>
</el-upload>
<el-progress :stroke-width="16" :percentage="progressPercent"></el-progress>
//上傳前對文件大小進行校驗
beforeUpload(file) {
const isLt2M = file.size / 1024 / 1024 < 50;
if (!isLt2M) {
this.$message.error('上傳文件大小大小不能超過 50MB!');
return isLt2M;
}
},
changeData (file, fileList) {
// 數(shù)據(jù)小于0.1M的時候按KB顯示
const size = file.size/1024/1024 > 0.1 ? `(${(file.size/1024/1024).toFixed(1)}M)` : `(${(file.size/1024).toFixed(1)}KB)`
file.name.indexOf('M')>-1 || file.name.indexOf('KB')>-1 ? file.name : file.name += size
},
handleRequest (data) {
let formdata = new FormData()
formdata.append('file', data.file)
const config = {
onUploadProgress: progressEvent => {
// progressEvent.loaded:已上傳文件大小
// progressEvent.total:被上傳文件的總大小
this.progressPercent = Number((progressEvent.loaded / progressEvent.total * 100).toFixed(2))
}
}
this.$axios.post(this.actionURL,formdata,config).then(res => {
if (res.data.code===1) {}
})
},