ElementUi 关于 el-upload的自定义上传(http-request)的使用

  

在开发中 遇到如下需求,要求前端传参并导入excel表格。导入失败,要弹出错误信息,同时导出错误信息的excel表格,导入成功提示信息即可。

1.原生方式导入文件

参考官方文档,把上传需要的属性加加入使用

  改造之前:

设置headers信息

2.自定义导入文件

在el-upload标签中加入http-request ,如下:

:http-request="importSonCodeRequest" //方法名

具体操作方法如下:

importSonCodeRequest(option){//option 这个参数会拿取到我们el_upload标签里我们配置信息
      if (this.classId=='' ){
        this.$message.warning("请选择归属模块!")
        return
      }
      if (this.codeId=='' ){
        this.$message.warning("请选择子码!") 
        return
      }
      var  data = new  FormData()//自定义 参数类型必须为 FormData格式 此为强制要求
      data.append("file",option.file)
      data.append("classId",this.classId)
      data.append("codeId",this.codeId)
      this.importCommit(data,option,'son')
    },
    //导入方法提交
 //data :为上传文件的参数, type :因为我有两个导入,我用类型来判断是哪个导入方法不需要去掉即可
    importCommit(data,option,type){
      axios({
        url: `${option.action}`,//取自el-upload标签的action中配置,或者也可以在这里直接写url
        method:"post",
        data:data,
        processData:false,
        contentType:false,
        headers: option.headers,//同理
        responseType: "blob",
        dataType: 'json',
      }).then(res => {
        if (res.data.size==0){
             this.$message.success("导入成功!")
          if (type=='son'){
            //刷新页面操作
          }else{
            //刷新页面操作
          }
        }else{
          this.errInfoExport(res)
        }
        this.$refs.importUpload.clearFiles()//清除上传成功的文件,非常重要,原因我下文写出来
      }).catch(err=>{
        //解析错误信息
        const fileReader = new FileReader()
        const errInfo =err.response.data
        fileReader.readAsText(err.response.data)
          fileReader.onloadend = () => {
          if (errInfo.type.indexOf("application/json") >-1) { // 说明是普通对象数据,包含错误提示信息
            const jsonData = JSON.parse(fileReader.result)
            // 后台错误信息
            this.$confirm(jsonData.message, "提示", {
              showCancelButton: false, //是否显示取消按钮
              type: "warning",
            }).then(() => {
            })
          }else{
            this.$message.error("导入失败!")
          }
          this.addListLoad = false;
          this.loading=false
          this.$refs.importUpload.clearFiles()
        }
      
      });
    },
 //错误信息导出方法封装
    errInfoExport(res){
      this.$message.error("导入失败!")
      this.addListLoad = false;
      const filename = decodeURIComponent("错误信息导出");//在这个定义导出文件的文件名
      const blob = new Blob([res.data], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'});
      if (window.navigator.msSaveBlob) {
        navigator.msSaveBlob(blob, filename);
      } else {
        const elink = document.createElement("a");
        elink.style.display = "none";
        elink.href = URL.createObjectURL(blob);
        document.body.appendChild(elink);
        elink.setAttribute("download", filename);
        document.body.appendChild(elink);
        elink.click();
        document.body.removeChild(elink);
        window.URL.revokeObjectURL(elink.href); // 释放URL 对象
      }
    },

 注意: 这里的Type是根据我们后端代码ExcelUtil工具类中的配置的,无论您的配置是啥,前后端必须要一致,否则导出的Excel文档将会是乱码!!

application/vnd.openxmlformats-officedocument.spreadsheetml.sheet

此外 :

//这行代码是是必须要使用的
this.$refs.importUpload.clearFiles() 

//用于清空上传组件中已选择的文件列表。将清空el-upload组件中已选择的文件列表。这个方法通常用于在用户选择了错误的文件或者需要重新选择文件时,清空已选择的文件列表

   这样el-upload的自定义上传文件的简单使用就完成了。当然如果只是单纯的上传文件没有其他额外的需求我还是推荐原生方式。

        感谢您看到这里,您的阅读就是我继续写作的动力!!能帮到您是我的荣幸,愿我们一同进步,加油!                                                                                                     

                                                                                                                       

  

  • 10
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
el-uploadElement UI 中的上传组件,它提供了多种上传方式,其中之一就是通过 http 请求上传文件。 使用 el-uploadhttp-request 属性可以指定上传文件的请求方法和请求地址。具体的用法如下: ```html <el-upload class="upload-demo" action="/upload" :http-request="uploadFile" > <el-button size="small" type="primary">点击上传</el-button> </el-upload> ``` ```javascript methods: { uploadFile(file) { // 创建 FormData 对象 const formData = new FormData(); // 将文件添加到 FormData 中 formData.append('file', file); // 发起上传文件的请求 return axios.post('/upload', formData, { headers: { 'Content-Type': 'multipart/form-data' } }).then(response => { // 文件上传成功的处理逻辑 console.log(response.data); }).catch(error => { // 文件上传失败的处理逻辑 console.error(error); }); } } ``` 在上述代码中,`http-request` 属性绑定了一个名为 `uploadFile` 的方法。当用户选择文件后,会调用该方法来处理文件上传的请求。在 `uploadFile` 方法中,我们创建了一个 `FormData` 对象,将用户选择的文件添加到其中,然后使用 `axios` 发起 POST 请求来上传文件。上传成功后,会执行 `then` 方法中的处理逻辑,上传失败则执行 `catch` 方法中的处理逻辑。 需要注意的是,由于涉及到文件上传,所以请求的 `Content-Type` 需要设置为 `multipart/form-data`,并且需要使用合适的后端接口来处理文件上传的请求。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值