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();
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章