vue el-upload实现多文件上传

这段代码展示了如何使用Element UI的上传组件实现文件上传、预览、删除和格式检查功能。用户可以选择多个doc或docx文件,上传前会进行格式验证,文件列表更新时会检查重复文件,支持上传到服务器并显示上传状态。此外,还提供了文件下载功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

代码:

<el-upload
          :auto-upload="false"
          multiple
          class="upload-demo"
          action="#"
          :on-change="uploadChange"
          :before-upload="handleBeforeUpload"
          :before-remove="beforeRemove"
          :on-remove="upLoadRemove"
          :on-preview="downLoadFile"
          :file-list="fileList"
        >
          <el-button size="small" icon="el-icon-plus" slot="trigger"
            >选取文件</el-button
          >
          <el-button
            style="margin-left: 10px"
            size="small"
            icon="el-icon-upload"
            type="success"
            @click="submitUpload"
            :disabled="fileList.length <= 0"
            >上传到服务器</el-button
          >
          <div class="el-upload__tip" slot="tip">仅限doc和docx文件</div>
        </el-upload>
 // 多文件上传
    fileUpload() {
      this.fileList = [];
      this.filedialogVisible = true;
    },
    // 上传前
    handleBeforeUpload(file) {
      console.log(file);
      // 校验
      let legalName = ["doc", "docx"];
      // 拿到后缀名
      let name = file.name.substring(
        file.name.lastIndexOf(".") + 1,
        file.name.length
      );
      if (legalName.includes(name)) {
        // console.log(legalName.includes(name));
      } else {
        this.$message.info("文件格式不对,仅限doc和docx");
        return false;
      }
    },

    // 拖拽上传
    beforeRemove(file, fileList) {
      this.fileList = fileList;
      // return this.$confirm(`确定移除 ${file.name}?`);
    },
    // 移除附件
    upLoadRemove(file, fileList) {
      let tempFileList = [];
      for (var index = 0; index < this.fileList.length; index++) {
        if (this.fileList[index].name !== file.name) {
          tempFileList.push(this.fileList[index]);
        }
      }
      this.fileList = tempFileList;
    },
    // 监控上传文件列l表
    uploadChange(file, fileList) {
      let existFile = fileList
        .slice(0, fileList.length - 1)
        .find((f) => f.name === file.name);
      if (existFile) {
        this.$message.error("当前文件已经存在!");
        fileList.pop();
      }
      this.fileList = fileList;
      // 校验
      let legalName = ["doc", "docx"];
      // 拿到后缀名
      let name = file.name.substring(
        file.name.lastIndexOf(".") + 1,
        file.name.length
      );
      if (legalName.includes(name)) {
        console.log(legalName.includes(name));
      } else {
        this.$message.info("文件格式不对,仅限doc和docx");
        return false;
      }
    },
    // 上传到服务器  formidable接收
    async submitUpload() {
      let formData = new FormData();
      this.fileList.forEach((item) => {
        formData.append("files", item.raw);
      });
      formData.append("parentId", this.allId);
      // append追加后console.log后仍为空,需要用formData.get("键")的方法获取值
      const res = await fileUpload(formData);
      console.log(res);
      if (res.status != 200) {
        return this.$message.error("上传失败");
      }
      this.$message.success("上传成功");
      this.fileBox(this.allId);
      this.filedialogVisible = false;
    },
    // 点击文件进行下载
    downLoadFile(file) {
      var a = document.createElement("a");
      var event = new MouseEvent("click");
      a.download = file.name;
      a.href = file.url;
      a.dispatchEvent(event);
    },
    //  :on-exceed="handleExceed"
    // 选取文件超过数量提示
    // handleExceed(files, fileList) {
    //   this.$message.warning(`当前限制选择 5 个文件,本次选择了 ${files.length} 个文件,共选择了 ${files.length + fileList.length} 个文件`);
    // },
`el-upload` 是 `ElementUI` 组件库中的一个组件,用于实现文件上传功能。它支持多文件上传、拖拽上传等功能,使用起来非常方便。以下是一个简单的示例: ```html <template> <div> <el-upload action="/api/upload" :data="{token: &#39;xxxxx&#39;}" :on-success="handleSuccess" :on-error="handleError" :multiple="true" :limit="3" :accept="&#39;image/*&#39;" ref="upload" > <el-button size="small" type="primary">点击上传</el-button> <div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过3个文件</div> </el-upload> </div> </template> <script> export default { methods: { handleSuccess(response, file, fileList) { console.log(response) console.log(file) console.log(fileList) }, handleError(error, file, fileList) { console.log(error) console.log(file) console.log(fileList) } } } </script> ``` 上面的代码中,我们将 `el-upload` 组件的 `action` 属性设置为上传文件的后端接口地址,`data` 属性设置为上传需要携带的参数,`on-success` 和 `on-error` 属性分别绑定了上传成功和上传失败的回调函数。`multiple` 属性表示是否支持多文件上传,`limit` 属性表示最多上传的文件数,`accept` 属性表示接受的文件类型。我们还使用了 `ref` 属性来获取到 `el-upload` 组件的引用,方便在其他方法中操作上传组件。 在上面的示例中,我们定义了 `handleSuccess` 和 `handleError` 两个方法来处理上传成功和上传失败的情况。在上传成功,我们可以通过 `response` 参数获取到服务器返回的数据,`file` 参数表示当前上传的文件,`fileList` 参数表示当前已经上传的文件列表。在上传失败,我们可以通过 `error` 参数获取到错误信息。 需要注意的是,以上示例只是前端实现上传文件的功能,你还需要在后端编写相应的代码来处理上传请求,将上传的文件保存到服务器上。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值