Vue2+ElementUI手動批量上傳文件支持不同文件參數名
需求說明:選擇指定2個不同格式的文件,點擊確認上傳后根據文件類型傳不同的參數名,如圖所示:

一個上傳文件接口,需要前端入參格式為:
{
xmlFile: file1,
pdfFile: file2,
...
}
主要代碼:
<el-upload action="" ref="upInvoice" :file-list="fileList" :multiple="true" :limit="2" :auto-upload="false" accept=".xml,.pdf" :on-change="invoiceUploadChange" :on-exceed="handleExceed" :on-remove="handleRemove" > <el-button slot="trigger" size="small" type="primary">選取文件</el-button> <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">確認上傳</el-button> <div slot="tip" class="el-upload__tip" style="color: #F56C6C;">需要上傳".xml"和".pdf"兩個文件,且單個文件大小不能超過10M!</div> </el-upload>
JS部分:
handleExceed() { this.$message.error("最多只能上傳兩個文件!"); }, handleRemove(file, fileList) { this.fileList = fileList }, invoiceUploadChange(file, fileList) { const fileType = /\.xml$|\.pdf$/i.test(file.name); if (!fileType) { this.$message.error("上傳發票的格式必須為xml或pdf!"); this.$refs.upInvoice.uploadFiles = fileList.filter(f => f.uid !== file.uid); return } const isLt2M = file.size / 1024 / 1024 < 10; if (!isLt2M) { this.$message.error("上傳發票的大小不能超過10m!"); this.$refs.upInvoice.uploadFiles = fileList.filter(f => f.uid !== file.uid); return } this.fileList = [...this.fileList, file]; }, // 發票上傳提交 submitUpload() { if (this.fileList.length !== 2 || this.fileList[0].raw.type === this.fileList[1].raw.type) { this.$message.error("請上傳.xml和.pdf兩個文件!"); return } const formData = new FormData(); formData.append('orderNo', '123456') for (let i in this.fileList) { if (this.fileList[i].raw.type === 'text/xml') { formData.append('xmlFile', this.fileList[i].raw); } else { formData.append('pdfFile', this.fileList[i].raw); } } this.upLoading = true axios.post('/api/upload', formData, { headers: { 'Content-Type': 'multipart/form-data', } }).then(res => { this.upLoading = false this.handleInvoiceSucess(res.data) }) },

浙公網安備 33010602011771號