后端返回的二进制文件流,前端jquery如何保持到本地?

使用ajax请求,后端返回给前端的文件流信息:!

image.png

前端使用jquery如何将它保存到本地,文件是PNG图片。

阅读 5.2k
4 个回答

你要看服务端返回数据的header里content-type是否是application/octet‑stream, 或者header里有没有Content-Disposition: attachment,只要有这两个其中一个,直接window.location.href= 链接,资源就自动下载到本地了,一般下载都是这么处理的,最好让后端配一下这两个其中一个

如果后端不方便配,或者其它原因,前端也是能处理的, 请求接口时让返回数据类型为 arrayBuffer, 原生ajax请求如下:

var xhr = new XMLHttpRequest();
xhr.open('GET', '/your/audio/file.wav', true);
xhr.responseType = 'arraybuffer';

xhr.onload = function(e) {
  if (this.status == 200) {
    //Do your stuff here
  }
};

xhr.send();

jquery的$.ajax貌似不支持arrayBuffer, 可以查查,其它像原生、fetch、axios都是支持的, 例如axios

const data = await axios.get(url, {
  responseType: 'arraybuffer',
});

拿到arrayBuffer数据后, 通过blob接受并下载, 如下

const blob = new Blob([data]);
const link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = fileName;
link.click();
window.URL.revokeObjectURL(link.href);

你这样子返回的不对。你应该最好返回base64串

let res = await axios.post('/api/export-excel', payload, {
      responseType: 'blob',
})
let fileName = 'test.xlsx'
let blob = res.data
if ('msSaveOrOpenBlob' in navigator) {
    // ie使用的下载方式
    window.navigator.msSaveOrOpenBlob(blob, fileName)
} else {
    let elink = document.createElement('a')
    // 设置下载文件名
    elink.download = fileName
    elink.style.display = 'none'
    elink.href = URL.createObjectURL(blob)
    document.body.appendChild(elink)
    elink.click()
    document.body.removeChild(elink)
}

先通过blob将二进制对象转换一遍,有了blob对象,后续你可以再转file对象或者转换为其他你可能需要的对象进行操作。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题