后端返文件流前端下载文件(常见的文件type类型)

连接的api接口

export function template(data) {
  return request({
    url: `接口地址`,
    method: 'post',
    data: data,
    // responseType: "arraybuffer"
      responseType: 'blob'
  })
}

前端进行下载


    downloadTemplate(){
      port.template().then(res=>{ 
            this.$message.success('下载成功')

        //创建
const url = window.URL.createObjectURL(new Blob([res], { type: "application/pdf;charset=utf-8" }))//返回的数据

        //const url = window.URL.createObjectURL(new Blob([res]))//返回的数据

            const link = document.createElement('a')
            link.style.display = 'none'
            link.href = url

            //自定义文件名称
            let date=new Date().Format("yyyyMMddhhmmss")
            link.setAttribute('download', '人员信息模版_' +date+ '.xls')//文件名
            
    //有些框架会将请求头屏蔽,然后直接返回文件流,这时候需要自己去单独写一个axios方法进行接口调用
    // 获取后端给前端返的请求头中的文件名称
    //const temp =res.headers["content-disposition"].split(";")[1].split("filename=")[1];
            //const name= decodeURIComponent(temp)



            document.body.appendChild(link)
            link.click()
            link.remove()
            window.URL.revokeObjectURL(url)
      })
    },

单独写axios进行下载

 //引入
import { getToken } from "@/utils/auth";
import axios from 'axios';
axios.defaults.headers['Authorization'] = 'Bearer ' + getToken();
axios.defaults.headers['Content-Type'] = 'application/pdf;charset=utf-8';


 
downloadTemplate() {
      let data={}
      axios({
          method: 'post',
          url: '接口地址',
          data: data,
          responseType: 'blob'
        }).then((res) => {
            // 文件流
            const content = res;
            const blob = new Blob([content]);
            //const blob = new Blob([content], { type: application/pdf;charset=utf-8 });
            let url = window.URL.createObjectURL(blob);
            let link = document.createElement("a");
            link.style.display = "none";
            link.href = url;
 
            // 获取后端给前端返的请求头中的文件名称
            const temp =res.headers["content-disposition"].split(";")[1].split("filename=")[1];
            const name= decodeURIComponent(temp)
    
            link.download = name
            document.body.appendChild(link);
            link.click();
            link.remove()
            window.URL.revokeObjectURL(url); //释放掉blob对象
      })
      .catch(error => {
        //console.log(error);
      });
    }

 常见的文件type类型

export function getFileType(name) {
  let arr = [
    { type: 'doc', application: 'application/msword' },
    {
      type: 'docx',
      application: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
    },
    { type: 'dot', application: 'application/msword' },
    {
      type: 'dotx',
      application: 'application/vnd.openxmlformats-officedocument.wordprocessingml.template',
    },
    { type: 'xls', application: 'application/vnd.ms-excel' },
    {
      type: 'xlsx',
      application: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    },
    { type: 'ppt', application: 'application/vnd.ms-powerpoint' },
    {
      type: 'pptx',
      application: 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
    },
    { type: 'pdf', application: 'application/pdf' },
    { type: 'txt', application: 'text/plain' },
    { type: 'gif', application: 'image/gif' },
    { type: 'jpeg', application: 'image/jpeg' },
    { type: 'jpg', application: 'image/jpeg' },
    { type: 'png', application: 'image/png' },
    { type: 'css', application: 'text/css' },
    { type: 'html', application: 'text/html' },
    { type: 'htm', application: 'text/html' },
    { type: 'xsl', application: 'text/xml' },
    { type: 'xml', application: 'text/xml' },
    { type: 'mpeg', application: 'video/mpeg' },
    { type: 'mpg', application: 'video/mpeg' },
    { type: 'avi', application: 'video/x-msvideo' },
    { type: 'movie', application: 'video/x-sgi-movie' },
    { type: 'bin', application: 'application/octet-stream' },
    { type: 'exe', application: 'application/octet-stream' },
    { type: 'so', application: 'application/octet-stream' },
    { type: 'dll', application: 'application/octet-stream' },
    { type: 'ai', application: 'application/postscript' },
    { type: 'dir', application: 'application/x-director' },
    { type: 'js', application: 'application/x-javascript' },
    { type: 'swf', application: 'application/x-shockwave-flash' },
    { type: 'xhtml', application: 'application/xhtml+xml' },
    { type: 'xht', application: 'application/xhtml+xml' },
    { type: 'zip', application: 'application/zip' },
    { type: 'mid', application: 'audio/midi' },
    { type: 'midi', application: 'audio/midi' },
    { type: 'mp3', application: 'audio/mpeg' },
    { type: 'rm', application: 'audio/x-pn-realaudio' },
    { type: 'rpm', application: 'audio/x-pn-realaudio-plugin' },
    { type: 'wav', application: 'audio/x-wav' },
    { type: 'bmp', application: 'image/bmp' },
  ];
    let type_node=arr.filter(item=>item.type==name);
    return type_node.length>0?type_node[0]:null
}

### 前端接收后端文件流并实现自动下载 为了实现在前端接收到由后端返回文件流并触发浏览器自动下载文件功能,可以采用基于 `axios` 发起 HTTP 请求的方式获取文件流,并利用 JavaScript 的 `Blob` API 创建文件对象。之后借助 `<a>` 标签模拟点击事件完成文件下载操作。 下面是一个完整的 Vue.js 方法用于发起请求以及处理响应中的文件流: ```javascript async function downloadFile() { try { const response = await axios({ method: 'get', url: '/api/download', // 后端提供文件流的API路径 responseType: 'blob' // 显式指定期望得到的是二进制大对象(BLOB) }); // 获取文件名可以从header中读取content-disposition字段解析出来, // 或者直接定义一个默认名称。 let filename = "default_filename"; const contentDisposition = response.headers['content-disposition']; if (contentDisposition) { const matches = /filename=([^;]+)/.exec(contentDisposition); if (matches != null && matches[1]) { filename = decodeURIComponent(matches[1].trim()); } } // 构建URL对象供<a>标签使用 const blob = new Blob([response.data]); const link = document.createElement('a'); link.href = URL.createObjectURL(blob); link.download = filename; // 将链接添加至DOM树以便触发click() document.body.appendChild(link); // 执行点击动作启动下载流程 link.click(); // 清理临时创建的对象防止内存泄漏 window.URL.revokeObjectURL(link.href); document.body.removeChild(link); } catch (err) { console.error(err.message || err); } } ``` 此方法适用于大多数场景下的文件下载需求,无论是文档还是图片等其他类型文件都可按照上述逻辑进行适配调整[^1]。 对于特定 MIME 类型的支持,比如 Excel 文件,则需确保设置正确的 Content-Type 头部信息给 `Blob` 构造器,例如 `"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"` 表示 `.xlsx` 文件格式[^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值