最近在項目中,使用了elementUI的<el-upload>做上傳文件,使用自定義:http-request的時候不顯示默認的進度條。
其實這個問題有兩種解決方案,一種是在action中直接寫上要上傳路徑的url,然后在on-success中獲取返回值的路徑(保存到服務器中,會返回url的路徑地址);另一種方法就是自定義進度條,也就是在:http-request后追加進度條
html:
<el-form-item ref="uploadElement" prop="fileUpdate" label="上傳文件">
<el-upload
class="upload-demo"
action="123"
:http-request="uploadSectionFile"
:before-remove="beforeRemove"
:limit="1"
:on-exceed="handleExceed"
:file-list="fileList"
accept=".apk"
>
<el-button size="small" type="primary">點擊上傳</el-button>
<el-progress style="width: 200px;margin-top: 8px" :text-inside="true" :stroke-width="20" :percentage="progressPercent" />
</el-upload>
</el-form-item>
js:
data() {
return {
progressPercent: 0, // 進度條默認為0
}
}
methods: {
/**
* 自定義上傳圖片的方法
*/
uploadSectionFile(params) {
// 上傳新文件時,將進度條值置為零
this.progressPercent = 0
const file = params.file
this.ruleForm.packageSize = (file.size / (1024 * 1024)).toFixed(2) + 'M' // 文件大小,轉化成M
this.forms = new FormData() // 實例化一個formData,用來做文件上傳
this.forms.append('file', file)
// 將圖片單獨上傳,並返回路徑
// 進度條
const uploadProgressEvent = progressEvent => {
this.progressPercent = Math.floor((progressEvent.loaded * 100) / progressEvent.total)
}
uploadFile(this.forms, uploadProgressEvent).then(res => {
if (res.code === 200) {
this.ruleForm.packageUrl = res.data.packageUrl
this.$refs.uploadElement.clearValidate() // 如果上傳文件成功,就把必填校驗動態移除
}
}).catch(response => {
console.log('文件上傳失敗')
})
},
}
最重要的是這個
const uploadProgressEvent = progressEvent => {
this.progressPercent = Math.floor((progressEvent.loaded * 100) / progressEvent.total)
}
然后在接口中,將參數傳過去
export function uploadFile(obj, onUploadProgress) {
return request({
url: '上傳的路徑',
method: 'POST',
data: obj,
headers: {
'Content-Type': 'multipart/form-data'
},
onUploadProgress
})
}