【Vue】搞文件的上传(导入)与下载(导出)

美好的一天开始啦,欢乐时光到了,摇摇晃晃~~吨吨吨
老规矩,先上官方上传方法:
链接: https://element.eleme.cn/#/zh-CN/component/upload.

文件上传

使用fromData来实现文件上传

<el-input type="text" readonly v-model="uploadFileName" value="uploadFileName" placeholder="请选择要导入的文件"></el-input>
<!-- <span class="filePrompt">文件后缀名为.xls或.xlsx</span> -->
</el-form-item>
<el-upload class="uploadStyle"
ref="fileImport"
:file-list="files"
:http-request="httpRequest"
:on-change="onchange"
accept="file">
<el-button type="primary" slot="trigger" @click="submitUpload"></el-button>
</el-upload>
// methods:
    // 获取文件名
    onchange(file, fileList) {
        const event = window.event;
        this.files = fileList.slice(- 1);
        if (event.target.files) {
            this.uploadFileName = event.target.files[0].name;
        }
    }
  httpRequest(file) {
      let formData = new FormData();
      formData.append('file', file.file);
      let config = {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      }
      axios.post('url', formdata, config)
    },
  submitUpload() {
     setTimeout(() => {
          this.$refs.fileImport.submit();
          this.uploadFileName = '';
      }, 1000);
  }

文件下载

通过获取文件信息,在网页上利用click事件,创建一个文件,然后将文件信息写入到文件中,然后保存

	let a = document.createElement('a'); // 创建元素节点a
    let href = window.URL.createObjectURL(Blob);//Blob:后端返回,包含文件下载的url
    a.href = href;
    a.download = `${name}.xlsx`; //name为自定义文件名,文件类型根据需求可自行修改
    document.body.appendChild(a);// 将a节点添加到document.body的末尾
    a.click();
    document.body.removeChild(a);
    window.URL.revokeObjectURL(href);

备注:如果请求接口的时候,将文件名(文件名包含中文或特殊字符)拼接到url里面的话,需要用encodeURIComponent进行编码!
感恩有你,江湖再会!┏(^0^)┛

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值