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)
  })
},

 

posted @ 2025-07-02 11:49  Oopy  阅读(78)  评论(0)    收藏  举报