element upload 多文件手動一次性上傳 文件重複性校驗

el upload 組件

<el-upload
        class="upload-demo"
        ref="upload"
        accept=".gif,.PDF"
        :action="batchImportDwgUrl"
        :on-change="onChange"
        :on-remove="onRemove"
        :file-list="fileList"
        :auto-upload="false"
        multiple>
        <el-button slot="trigger" size="small" type="primary" >選擇圖紙</el-button>
        <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">確定所選圖紙</el-button>
      </el-upload>

accept=".gif,.PDF" 指定屬性文件選擇時候的類型
:auto-upload=“false” false指定手動上傳

accept 指定的效果
在這裏插入圖片描述

上傳效果:
在這裏插入圖片描述

vue return 裏邊的關鍵變量定義

fileList: [],
msgPromise: Promise.resolve(),
batchImportDwgUrl: '',

文件上傳的方法:

// 文件手動上傳
    submitUpload() {
      // 當前沒有選擇任何文件,不調用方法
      if(this.fileList.length === 0){
        return false
      }

      // this.$refs.upload.submit();
      let uploadForm = new FormData()
      uploadForm.append("orderNo", this.newOrderForm.orderNo);
      uploadForm.append("customer", this.newOrderForm.customer);
      uploadForm.append("urgentLevel", this.newOrderForm.urgentLevel);
      uploadForm.append("orderDate", formatDate(this.newOrderForm.orderDate, "yyyy-MM-dd"));
      uploadForm.append("orderDeliverDate", formatDate(this.newOrderForm.orderDeliverDate, "yyyy-MM-dd"));
      for(let i=0;i<this.fileList.length;i++){
        uploadForm.append("file",this.fileList[i].raw);
      }

      this.$axios.post(importDrawingUrl, uploadForm, {
        headers: {
          'keyId': token,
          'Content-Type': 'multipart/form-data;charset=UTF-8',
          "Accept": "*/*"
        }
      }).then(response => {
        if (response.data.code !== '0000') {
          Notification.warning({
            title: '導入圖紙失敗!',
            message: response.data.msg,
            duration: 5000
          })
          return false;
        }
        // 把當前上傳成功的圖紙添加到列表
        for (const data of response.data.data) {
          this.newOrderTableData.push(data)
        }
        // 把當前已經確認導入成功的圖紙保存起來
        for (const file of this.fileList) {
          this.confirmCurrentSelectFileList.push(file)
        }
        // 關閉窗體,清空所選文件列表
        this.fileList = []
        this.clearFiles()
        this.importDialogVisible = false
        console.log("當前確定成功的文件列表:")
        console.log(this.confirmCurrentSelectFileList)
      })

    },
        onChange(file,fileList){
      //這表示是添加行爲
      // console.log(`準備修改文件${file.raw.name}, 此時文件列表長度爲${fileList.length}`);
      if (file.status==='ready') {
        console.log(`添加了文件${file.raw.name}`);
        let myFile = file.raw;

        const type = myFile.type.toLowerCase();
        const isPDF = type === 'application/pdf';
        if (!(isPDF)) {
          // 關鍵作用,如果文件有問題直接不追究
          fileList.pop();
          this.handleMsg('上傳的文件格式不正確', 'error');
          // 無論是不是增加新文件都更新長度信息
          return;
        }

        // 存在文件標識
        let existsFileFlag = false;

        for(let i=0; i < this.fileList.length; i++){
          if( (file.name === this.fileList[i].name) && (file.size === this.fileList[i].size) ) {
            // 如果存在了,賦值true
            existsFileFlag = true;
          }
        }

        // 遍歷的這個文件存在當前列表直接結束
        if(existsFileFlag){
          // 否則不加入
          fileList.pop();
          // console.log(`文件已經存在:${file.name}`)
          // this.handleMsg(`文件已經選擇過了:${file.name})`);
          Notification.warning({
            title: '文件重複提示:',
            message: `文件已經選擇過了:${file.name})`,
            duration: 5000
          })
          return;
        }


        // 判斷當前選擇的圖紙,和當次已經 確定所選圖紙 是否重複
        let existsAllFileFlag = false;
        for(let i=0; i < this.confirmCurrentSelectFileList.length; i++){
          if( (file.name === this.confirmCurrentSelectFileList[i].name) && (file.size === this.confirmCurrentSelectFileList[i].size) ) {
            // 如果存在了,賦值true
            existsAllFileFlag = true;
          }
        }
        if(!existsAllFileFlag){
          this.fileList.push(file);
        } else {
          // 否則不加入
          fileList.pop();
          Notification.warning({
            title: '文件重複提示:',
            message: `當前選擇的文件已經上傳過了,請查看新建訂單列表去確認:${file.name}`,
            duration: 5000
          })
          // this.handleMsg(`當前選擇的文件已經上傳過了,請查看新建訂單列表去確認:${file.name}`);
          return;
        }

        console.log('最終添加的列表:')
        console.log(this.fileList)

      }

    },
    handleMsg(message, type = 'info') {
      const duration = 1500;
      //一定要this.msgPromise = XXX纔有用,這樣後調用的纔會.then接到後面
      //Promise.then().then()和Promise.then(); Promise.then();是不一樣的,前者是真串行
      this.msgPromise = this.msgPromise.then(() => {
        this.$message({message, type, duration});
      });
    },


    onRemove(file,fileList){
      this.fileList = fileList;
    },

java 後端Controler接口:

    /**
     * 批量圖紙導入, 僅支持PDF文件
     */
    @ApiOperation(value = "導入:圖紙導入")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderNo", value="訂單號", required=true, paramType="query"),
            @ApiImplicitParam(name = "customer", value="客戶", required=true, paramType="query"),
            @ApiImplicitParam(name = "urgentLevel", value="緊急程度", required=true, paramType="query"),
            @ApiImplicitParam(name = "orderDate", value="訂單日期 ", required=true, paramType="query"),
            @ApiImplicitParam(name = "orderDeliverDate", value="訂單交期", required=true, paramType="query")
    })
    @PostMapping(value = "/importDrawing", produces = {MediaType.APPLICATION_JSON_UTF8_VALUE},consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public ResultUtils importDrawing(@RequestParam(value = "file") MultipartFile[] files,
                                     @RequestParam(value = "orderNo") String orderNo,
                                     @RequestParam(value = "customer") String customer,
                                     @RequestParam(value = "urgentLevel") String urgentLevel,
                                     @RequestParam(value = "orderDate") String orderDate,
                                     @RequestParam(value = "orderDeliverDate") String orderDeliverDate){

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        SalesAccountRequestVO salesAccountRequestVO = new SalesAccountRequestVO();
        salesAccountRequestVO.setOrderNo(orderNo);
        // 這裏使用訂單號來做identification的文件標識
        salesAccountRequestVO.setIdentification(orderNo);
        salesAccountRequestVO.setCustomer(customer);
        salesAccountRequestVO.setUrgentLevel(urgentLevel);
        salesAccountRequestVO.setOrderDate(DateUtils.stringToDate(orderDate, format));
        salesAccountRequestVO.setOrderDeliverDate(DateUtils.stringToDate(orderDeliverDate, format));

        ResultUtils resultUtils = salesAccountService.importDrawing(files, salesAccountRequestVO);
        return resultUtils;
    }

主要關注的關鍵代碼:
在這裏插入圖片描述

可以私信我交流學習!!!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章