后端给接口, 前端下载文件

文章讲述了如何使用axios库进行接口请求,特别是处理返回类型为arraybuffer的文件下载。通过设置responseType为arraybuffer,然后利用blob对象和自定义的resolveBlob函数,解析并触发文件下载,同时解决了文件名和编码问题。
摘要由CSDN通过智能技术生成

接口书写 , 注意接口添加 responseType: 'arraybuffer'

import { axios } from '@/utils/request'
export const downloadStandard = () => {
  return axios.get(`${DATAEXCHANGE}/demandManagement/downloadFile?fileName=pg字段对接.txt`,     {
    responseType: 'arraybuffer'
  })
}

 点击下载触发自定义事件 , 获取数据 ,如果不经过resolveBlob方法处理 , res的中文是乱码状态

downloadStandard().then((res) => {
        resolveBlob(res, 'arraybuffer', 'xxx.txt')
      })

处理res数据 , 使用resolveBlob即可

import axios from 'axios'
import storage from 'store'

const baseUrl = process.env.VUE_APP_BASE_API
export function downLoadZip(str, filename) {
  const url = baseUrl + str
  axios({
    method: 'get',
    url: url,
    responseType: 'blob',
    headers: { Authorization: 'Bearer ' + storage.get(ACCESS_TOKEN_AUTH) }
  }).then((res) => {
    resolveBlob(res, mimeMap.zip)
  })
}

/**
 * 解析blob响应内容并下载
 * @param {*} res blob响应内容
 * @param {String} mimeType MIME类型
 * @param {String} fileName 文件名
 */
export function resolveBlob(res, mimeType, fileName) {
  const aLink = document.createElement('a')
  const blob = new Blob([res.data], { type: mimeType })
  if (!fileName) {
    const patt = /filename=([^;]+\\.[^\\.;]+);*/
    const contentDisposition = decodeURI(res.headers['content-disposition'])
    const result = patt.exec(contentDisposition)
    fileName = result[1].replace(/"/g, '')
  }
  aLink.href = URL.createObjectURL(blob)
  aLink.setAttribute('download', fileName) // 设置下载文件名称
  document.body.appendChild(aLink)
  aLink.click()
  document.body.appendChild(aLink)
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值