Bootstrap

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());
    });
};

;