gpt4 book ai didi

javascript - 从ajax下载数据文件

转载 作者:行者123 更新时间:2023-11-30 09:58:38 24 4
gpt4 key购买 nike

我正在尝试通过 ajax 启动文件下载。我可以从服务器检索数据,但无法让浏览器打开数据。我不能只将浏览器的 location.href 指向端点 url。

我要下载的资源通过需要自定义 http header 和身份验证承载 token 的端点公开。我无法更改后端 api 以允许 cookie。因此,我不能只用 window.open(url,'_blank')

打开 url

我可以向端点发出 ajax 请求,但我不知道在收到响应后如何下载文件。

$.get( "restAPI/file.pdf", function( data ) {
var w = window.open(null,'_blank')
$(w.document.body).html(data);
});

也不行

我希望做类似的事情

var w = window.open(data,'_blank')

但这也不起作用。

编辑

解决方案,感谢 joyBlanks

   $http({method: 'GET',
responseType:'arraybuffer',
headers: {
Accept: 'application/octet-stream',
}, url:url }
).then(function(data) {
var blob = new Blob([data.data]);

if (window.navigator.msSaveBlob)
window.navigator.msSaveBlob(blob, filename);
else {
var link = document.createElement('a');
link.id = filename;
link.href = window.URL.createObjectURL(blob);
link.download = filename;
link.click();
}
});

最佳答案

现代浏览器支持 download <a> 的属性标签。

This attribute, if present, indicates that the author intends the hyperlink to be used for downloading a resource so that when the user clicks on the link they will be prompted to save it as a local file. If the attribute has a value, the value will be used as the pre-filled file name in the Save prompt that opens when the user clicks on the link (the user can change the name before actually saving the file of course). There are no restrictions on allowed values (though / and \ will be converted to underscores, preventing specific path hints), but you should consider that most file systems have limitations with regard to what punctuation is supported in file names, and browsers are likely to adjust file names accordingly.

注意:可与 blob: URL 和 data: URL 一起使用,使用户可以轻松下载使用 JavaScript 以编程方式生成的内容(例如,使用在线绘图 Web 应用程序创建的图片)。如果 HTTP header Content-Disposition: 存在并给出与此属性不同的文件名,则 HTTP header 优先于此属性。如果此属性存在并且 Content-Disposition: 设置为内联,则 Firefox 优先考虑 Content-Disposition,例如文件名大小写,而 Chrome 优先考虑 download 属性。此属性仅适用于指向同源资源的链接。

<a download src="restAPI/file.pdf">Download File</a>

因此,当您单击 a 标签时,它会显示一个弹出窗口,用于下载该文件。从请求中我可以看到该文件已经可用。

您可以阅读更多:https://developer.mozilla.org/en/docs/Web/HTML/Element/a

关于javascript - 从ajax下载数据文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32725530/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com