在vue中实现文件的上传

vue+element实现文件上传

我们这里使用element-ui中的upload组件来实现文件的上传下载(https://element.eleme.cn/#/zh-CN/component/upload#shou-dong-shang-chuan),这里我们以excel文件为例
<el-upload
         class="upload-demo"
         ref="upload"
         :limit="1"
         :before-upload="beforeUpload"
        accept=".xls,.xlsx"    //限制选择文件的格式
      >
         <el-button
          class="btn"
          slot="trigger"
          size="small"
          type="primary"
          style="margin-right: 20px"
        >导入模板</el-button>

      </el-upload> 
 beforeUpload(file) {
      // console.log(file,'文件');
      this.files = file;
      const extension = file.name.split(".")[1] === "xls";
      const extension2 = file.name.split(".")[1] === "xlsx";
      const isLt5M = file.size / 1024 / 1024 < 5;
      if (!extension && !extension2) {
        return;
      }
      if (!isLt5M) {
        return;
      }
      this.fileName = file.name;
      setTimeout(() => {
        this.submitUpload();
      }, 500);
      return false; // 返回false不会自动上传
    },

    // 上传文件
    submitUpload() {
      if (this.fileName == "") {
        this.$message.warning("请选择要上传的文件!");
        return false;
      }
      let fileFormData = new FormData();
      var json = { id: "123" };
      fileFormData.append("json", JSON.stringify(json));
      //filename是键,file是值,就是要传的文件,test是要传的文件名
      fileFormData.append("file", this.files);
      let requestConfig = {
        headers: {
          "Content-Type": "multipart/form-data;charset=UTF-8"
        }
      };
      // 执行上传文件
      let id = "";
      this.$http
        .post("url", fileFormData, requestConfig)
        .then(resp => {
          if (resp.data.status != 200) {
          } else {
            id = resp.data.result[0].attachmentId;
          }
        })
  • 1
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值