el-upload手动上传多个文件

使用el-upload手动上传多个文件

引入组件el-upload

 <el-upload style=""
                     class="upload-demo"
                     ref="upload"
                     :limit="fileLimit"
                     drag
                     action=""
                     :on-preview="handlePreview"
                     :on-remove="handleRemove"
                     :on-exceed="handleExceed"
                     :before-remove="beforeRemove"
                     :before-upload="beforeUpload"
                     :on-change="handleChange"
                     :auto-upload="false">
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处,或<em>点击上传</em></div>
            <div class="el-upload__tip" slot="tip">最多{{this.fileLimit}}个附件,每个附件不超过{{this.fileSizeLimitByMb}}MB</div>
          </el-upload>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取 消</el-button>
            <el-button type="primary" @click="dialogFormVisible = false">确 定</el-button>
          </div>

注意el-upload中有许多的钩子函数,比如before-remove,在移除文件前会触发。

Axios通过post发送多个文件

首先我们需要找到这些文件,我定义了一个Map,记录<文件名,文件>。
在handleChange钩子函数中,把文件加入该map,因为这个钩子被触发时表示有新的文件加入:

      handleChange(file, fileList) {
        console.log("handleChange", file, fileList)
        // 添加文件时触发:file.raw才是原始文件类型
        this.fileMap.set(file.name, file.raw);
      }

handleRemove是处理移除文件的,如果被调用,表明文件被移除,也应该从Map中移除。

      handleRemove(file, fileList) {
        this.fileMap.delete(file.name)
      }

那么我们就通过一个Map记录下了所有的文件,现在如何上传?

我们知道,在HTTP请求报文中,formdata是一种专门传输文件的Content-Type,那么我们就创建一个FormData对象,把文件存进去,然后传输即可。

  let fileFormData = new FormData(); // 这是需要发送的文件formdata
  for (let val of this.fileMap.values()){
    fileFormData.append("file", val);
  }

注意:这里这里所有的文件都添加到"file"这个名称下,那么就会自动形成一个文件数组。

除此之外,我们还可以添加其他参数,如:

fileFormData.append("subject", this.emailForm.subject);
fileFormData.append("content", this.emailForm.content);

后端如何接收文件?

我使用的是Spring框架,后端MultipartFile类型专用来接收文件。如:

    @PostMapping(value = "/send")
    public Response send(@RequestParam("emails") String emails,
                         @RequestParam("subject") String subject,
                         @RequestParam("content") String content,
                         @RequestParam("file") MultipartFile[] multipartFiles){
        System.out.println(emails+" | "+subject+" | "+content);
        System.out.println("multipartFiles:"+ multipartFiles.length);
        for (MultipartFile file : multipartFiles) {
            System.out.println(file.getOriginalFilename());
        }
        return emailService.send();
    }
原文地址:https://www.cnblogs.com/XT-xutao/p/14826659.html