Ajax 下载文件 文件被损坏

问题表现

Ajax 下载文件成功后,打开提示格式损坏,源代码如下:

  axios({
    method: 'get',
    url: "/public/工作簿1.xlsx", // 静态资源地址
  }).then(res => {
    const href = document.querySelector('.href')
    let blob = new Blob([res.data], { type: 'application/octet-stream'})
    href.href = URL.createObjectURL(blob)
    href.download = "xxx.xlsx"
    href.click()
  })

提示格式被损坏:

将 responseType 设置为 blob 或者 arraybuffer 即可:

  axios({
    method: 'get',
    url: "/public/工作簿1.xlsx", // 静态资源地址
    responseType: 'blob'
  }).then(res => {
    const href = document.querySelector('.href')
    let blob = new Blob([res.data], { type: 'application/octet-stream'})
    href.href = URL.createObjectURL(blob)
    href.download = "xxx.xlsx"
    href.click()
  })

原因探索

responseType 的作用用于告诉浏览器,如何解析服务端返回的数据,需要保证客户端所设置的 responseType,能够解析服务端返回的内容类型( content-type),否则会导致格式解析错误,先看 responseType 所支持的类型:

类型 说明
"" responseType 为空字符串时,采用默认类型 DOMString,与设置为 text 相同
"arraybuffer" response 是一个包含二进制数据的 JavaScript ArrayBuffer
"blob" response 是一个包含二进制数据的 Blob 对象
"document" response 是一个 HTML Document 或 XML XMLDocument,这取决于接收到的数据的 MIME 类型。
"json" response 是一个 JavaScript 对象。这个对象是通过将接收到的数据类型视为 JSON 解析得到的。
"text" response 是一个以 DOMString(UTF-16字符串) 对象表示的文本

当后台返回的数据是二进制数据流时,我们必须指定客户端也是以二进制流的方式去解析,否则无法获取到期望的结果。在上面的例子中,我们未设置 responseType,所以默认的解析方式为 DOMString,导致数据不一致。

原文地址:https://www.cnblogs.com/GManba/p/13123766.html