天天看點

el-upload上傳檔案大小限制

el-upload上傳檔案大小限制

當我們在使用element做上傳檔案的時候,會有要求做上傳檔案的大小限制這個需求,今天我們就來講一下限制大小這個功能:

首先先講一下流程,當檔案超過20MB的時候讓他提示

檔案大小不能超過20MB,請重新上傳。

下面我們來看代碼:

<el-upload
   class="upload-demo" ref="upload" name="upload" :action="action()"
    :on-change="(file, fileList) => {handleChange(file, fileList, scope);} "
    :on-remove=" (file, fileList) => {handleRemove(file, scope);}"
    :file-list="scope.row.fileList"
    :auto-upload="false"
     >
       <el-button  slot="trigger" size="mini" type="primary" v-if="scope.row.fileList.length == 0" >上傳檔案</el-button>
</el-upload>
           
首先在el-upload的:on-change事件裡的handleChange的方法中可以擷取上傳檔案的大小
handleChange(file, fileList, scope) {
		//擷取上傳檔案大小
      let imgSize = Number(file.size / 1024 / 1024);

      if (imgSize > 20) {
        this.$msgbox({
          title: "",
          message: "檔案大小不能超過20MB,請重新上傳。",
          type: "warning",
        });
        this.materialList[scope.$index].fileList.splice(scope.index, 1);
        return;
      } 
      this.text = "上傳中";

      this.loading = true;
      this.materialList[scope.$index].fileList.push(file);
      let data = new FormData();
      data.append("files", file.raw);
      uploadFile(data, scope.row.materialName).then((response) => {
        if (response.success) {
          this.loading = false;
          this.listedFiles[scope.$index] = response.result[0].id;
        } else {
          this.loading = false;
          this.msgError(response.message || "操作失敗");
        }
      });
    },
           

以上就是一個完整的例子,希望對你有所幫助

vue