1个回答

test
2024-07-17
你要看服务端返回数据的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);
回复

适合作为回答的
- 经过验证的有效解决办法
- 自己的经验指引,对解决问题有帮助
- 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
- 询问内容细节或回复楼层
- 与题目无关的内容
- “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容