vue3实现文件上传、文件下载

一、文件上传

(1).template

  1. multiple :支持多选
  2. limit="100" : 限制最多100个文件
  3. accept=".dbc":限制上传文件的类型
<el-upload
  ref="uploadRef"
  v-model:file-list="ruleForm.DBCfile"
  multiple
  :limit="100"
  :auto-upload="false"
  :on-change="handleChangeFile"
  accept=".dbc"
>
  <template #trigger>
     <el-button plain type="primary">Select Local Files</el-button>
  </template>

</el-upload>

(2).js

文件上传使用formData格式

const uploadRef = ref();
const fileLists = ref([]);

// 文件改变时执行
const handleChangeFile = (file, fileList) => {
  if (!file) return;

  //限制上传文件大小
  const fileSize = file.size / 1024 / 1024;
  if (fileSize > 10) {
    const currIdx = fileList.indexOf(file);
    fileList.splice(currIdx, 1);
    proxy.$modal.msgError(`The maximum size of each file is 10M.`);
  }

  // 文件重复上传
  fileLists.value.forEach((item) => {
    if (item.name == file.name) {
      const currIdx = fileList.indexOf(file);
      fileList.splice(currIdx, 1);
      proxy.$modal.msgError(`File already exist.`);
    }
  });
  fileLists.value = fileList;


 //文件上传接口需要formData格式
  fileList.forEach((item) => {
    formData.value.append("file", item.raw, item.name);
  });
};

调用接口时传入 formData

二、文件下载

(1).template

<el-button @click="handleExport()">Export</el-button>

(2).js

const handleExport = () => {
  exportDbc(id)  //接口地址
    .then((res) => {
      let blob = new Blob([res]);
      let url = window.URL.createObjectURL(blob); // 创建 url 并指向 blob
      let a = document.createElement("a");
      a.href = url;
      a.download = `arxml.zip`;
      a.click();
      window.URL.revokeObjectURL(url); // 释放该 url
    })
    .catch((error) => {
      reject(error.toString());
    });
};

  • 4
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值