elementUI實現(xiàn)自定義上傳文件并攜帶參數(shù)

vue代碼

<el-upload
    ref="upload"
    action="/api/iot/deviceInfo/uploadFiles"
    :before-upload="beforeUploadHandle"
    :on-success="handleSuccess"
    :auto-upload="false"
    multiple
    :limit="2"
    :on-exceed="handleExceed"
    :file-list="fileList">
     <el-link :disabled="disabled" icon="el-icon-paperclip" type="primary">添加文檔或視頻</el-link>
 </el-upload>

js代碼

 // 上傳之前
    beforeUploadHandle(file) {
      // 校驗格式
      if (
        file.type !== "video/mp4" &&
        file.type !== "application/msword" &&
        file.type !==
          "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
      ) {
        this.$message.error("只支持.mp4、.doc、.docx文件!");
        return false;
      }
    },
    // 超出上傳數(shù)量的時候調(diào)用
    handleExceed(files, fileList) {
      this.$message.warning(
        `當(dāng)前限制選擇 2 個文件,本次選擇了 ${files.length} 個文件,共選擇了 ${
          files.length + fileList.length
        } 個文件`
      );
    },
    // 手動上傳
    submitUpload() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          if (this.$refs.upload.uploadFiles.length <= 0) {
            this.$message.warning("請選擇上傳的文檔或視頻");
            return;
          }
          this.saveLoading = true;
          // 新建formData對象
          let formData = new FormData();
          // 將上傳的文件放進formData對象
          this.$refs.upload.uploadFiles.forEach((file) => {
            formData.append("file", file.raw);
          });
          // 攜帶其他參數(shù)
          formData.append("articleTitle", this.form.articleTitle);
          formData.append("category", this.form.category);
          formData.append("author", this.form.author);
          formData.append("keyword", this.form.keyword);
          formData.append("unit", this.form.unit);
          // 調(diào)用上傳接口
          uploadFile(formData)
            .then((res) => {
              if (res && res.code === 200) {
                this.$message.success("保存成功");
              } else {
                this.$message.error(res.msg);
              }
              this.saveLoading = false;
              this.queryRule();
            })
            .catch((err) => {
              console.log(err);
            });
          this.dialogFormVisible = false;
          this.isAdd = false;
        }
      });
    },

使用this.$refs.upload.uploadFiles獲取文件列表是因為通過綁定file-list經(jīng)常獲取不到對象列表,具體原因還不清楚

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容