如何自定义文件下载,可以自定义文件名?

文件已经处理过跨域

阅读 710
2 个回答
✓ 已被采纳

使用a标签自定义文件名有跨域限制,还有浏览器兼容性问题

import {saveAs} from 'file-saver';

export const fileType = () => {
    return {
        pdf: 'application/pdf',
        docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
        xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        xls: 'application/vnd.ms-excel',
        doc: 'application/msword',
        ppt: 'application/vnd.ms-powerpoint',
        pptx: 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
    };
};


/**
 * @description 根据url下载文件
 * @param fileUrl 文件地址
 * @param customFileName 文件名称
 * @param fileExtension 文件后缀
 * @returns
 */
export const downFetchFile = async (
    fileUrl: string,
    customFileName: string,
    fileExtension: string
) => {
    if (!fileUrl || !customFileName || !fileExtension) {
        throw new Error('缺少必传参数');
        return;
    }

    const type = fileType();

    try {
        const response = await fetch(fileUrl);

        if (!response.ok) {
            throw new Error('Network response was not ok');
        }

        const blob = await response.blob();
        const zipBlob = new Blob([blob], {type: type[fileExtension]});
        saveAs(zipBlob, `${customFileName}.${fileExtension}`);
    } catch (error) {
        console.error('Error downloading file:', error);
    }
};

文件流下载的可以
export const fileDownload = (id) => get(/file/download/${id}, { responseType: 'blob' })

async handleDown(id) {
  this.loadingText = '正在下载,请稍候'
  this.loading = true
  try {
    let res = await fileDownload(id)

    console.log(res.data, 'res.data')
    const blob = new Blob([res.data])
    const reader = new FileReader()
    reader.readAsDataURL(blob)
    reader.onload = e => {
      const filename = res.headers['content-disposition'].split('filename=')[1]  //或者可以改成自定义的文件名称
      const a = document.createElement('a')
      a.download = decodeURIComponent(filename)
      a.href = e.target.result
      document.body.appendChild(a)
      a.click()
      document.body.removeChild(a)
    }
    this.loading = false
    this.$message.success('文件导出成功')
  } catch (e) {
    throw new Error(`下载文件 ${item.name} 失败`)
  }
},
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题