需求:Vue項(xiàng)目中使用element-ui的el-upload上傳文件,由于頁面中除了文件上傳,還有表單數(shù)據(jù)需要一起提交,所以不能使用el-upload的默認(rèn)上傳,而官方文檔提供了http-request自定義上傳方法來覆蓋組件默認(rèn)的上傳方式,如下圖:

image.png
所以我們可以在自定義上傳方法中,配合使用axios來提交上傳文件
需要注意的是:
自定義的上傳方式就是模擬html表單上傳文件,所以我們使用new FormData()來向后臺(tái)傳送文件,
而el-upload上傳文件是一個(gè)一個(gè)文件上傳的,所以我們可以在on-change函數(shù)里面遍歷fileList,把每個(gè)子項(xiàng)的 raw(File文件) 取出來,放在一個(gè)數(shù)組里面保存,在自定義上傳方法里,用FormData格式,每次取數(shù)組中的第一個(gè)進(jìn)行遞歸上傳,每取一個(gè)文件,上傳文件數(shù)組里就刪除一個(gè),數(shù)組為空則不再遞歸運(yùn)行(自定義上傳方法),具體代碼如下:
<template>
<div class="inside-base">
<div class="up-filebox">
<i class="tips" v-show="showUpFile">可上傳pdf、ppt、word、excel等不超過25M</i>
<el-upload
action=""
:auto-upload="false"
:multiple="true"
:http-request="myUploadFile"
accept=".pdf,.PDF,.doc,.docx,.xls,.xlsx,.ppt,.pptx"
:file-list="fileList"
:on-change="onChangeFile"
:before-remove="beforeRemove"
:on-remove="onRemoveFile"
>
<a href="javascript:;" v-show="showUpFile">
<i class="el-icon-upload"></i>
<p>點(diǎn)擊上傳</p>
</a>
</el-upload>
</div>
</div>
</template>
<script>
export default {
name: '',
data () {
return {
fileList: [], // // 上傳文件列表
upFile: [], // 文件File 上傳參數(shù)
upFileList: [] // 文件File列表 上傳參數(shù)
}
},
methods: {
// 選擇上傳文件
onChangeFile (file, fileList) {
const isLt25M = file.size / 1024 / 1024 < 25
if (!isLt25M) {
this.$msgbox.alert('上傳文件大小不能超過 25MB!')
return false
}
this.upFileList = []
for (let x of fileList) {
if (x.raw) {
this.upFileList.push(x.raw)
}
}
},
// 移除文件之前
beforeRemove (file, fileList) {
return this.$msgbox.alert(`確定移除 ${file.name}?`)
},
// 移除文件
onRemoveFile (file, fileList) {
this.upFileList = []
for (let x of fileList) {
if (x.raw) {
this.upFileList.push(x.raw)
}
}
},
// 請(qǐng)求 上傳產(chǎn)品文件 接口
myUploadFile () {
this.upFile = this.upFileList.shift()
let uploadForm = new FormData()
uploadForm.append('uid', this.$store.state.mutations.userId)
uploadForm.append('token', this.$store.state.mutations.userToken)
uploadForm.append('file', this.upFile)
this.$api.pProductFile(uploadForm).then(response => {
console.log(response)
if (this.upFileList.length === 0) {
this.upFile = ''
return false
} else {
this.myUploadFile()
}
}).catch(error => {
console.log(error.response)
this.$msgbox.alert(error.response.data.message, {
callback: action => {
if (error.response.data.message === 'token驗(yàn)證失敗') {
this.$router.push({ path: '/login' })
}
}
})
})
}
}
}
</script>
<style scoped>
</style>