前端上传、下载文件

211 阅读1分钟

文件下载

前端下载文件常见的两种方式

  1. 后台提供一个 URL,然后用 window.open(URL) 下载
  2. 后台直接返回文件的二进制内容,然后前端转化一下再下载。

方式二:

Blob、ajax(axios)

mdn 上是这样介绍 Blob 的:

Blob 对象表示一个不可变、原始数据的类文件对象。Blob 表示的不一定是JavaScript原生格式的数据

具体使用方法

axios({
    method: 'post',
    url: '/export',
    responseType: 'arraybuffer',
}).then(res => {
    // 假设 data 是返回来的二进制数据
    const data = res.data;
    const url = window.URL.createObjectURL(new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }));
    const link = document.createElement('a');
    link.style.display = 'none';
    link.href = url;
    link.setAttribute('download', 'excel.xlsx');
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
});

注: 打开下载的文件,看看结果是否正确。 若文件下载后打开错误或者出现乱码,需要查看参数 responseType,它表示服务器响应的数据类型,由于后台返回来的是二进制数据,所以我们要把它设为 arraybufferblob

文件上传

// 获取文件后缀名,当前只支持 .dat 后缀的文件
const suffix = file.name?.substring(file.name?.lastIndexOf('.') + 1);
if (!supportFileSuffix.includes(suffix)) {
    this.loadingStatus = uploadStatus.fail;
    return this.handleFormatError(file);
}
// 限制文件大小 1MB 内
if (file?.size > 1024 * 1024) {
    this.loadingStatus = uploadStatus.fail;
    return this.handleSizeError();
}
const formData = new FormData();
formData.append('file', file);
try {
    const res = await fileUpload(formData);
    if (res.code === '200') {
        this.formValidate.protocolCertificateAddr = res.data.filePath;
        this.loadingStatus = uploadStatus.success;
    } else {
        this.loadingStatus = uploadStatus.fail;
    }
} catch (res) {
    this.loadingStatus = uploadStatus.fail;
}