使用 Javascript 触发 CSV 下载?
我有一个 url /reportcsv
,它生成一个带有 Content-type: text/csv
和 Content-disposition:attachment; 的纯文本 csv;文件名=报告.csv
。我想触发使用 Javascript 下载此 csv。我正在考虑两种方法:
1) 设置 location.href = /reportcsv
2) 将 iframe url 设置为 /reportcsv
这两种方法似乎都可以在 Safari 中使用。我想知道它们之间是否有什么区别,或者是否推荐其中一个。我的主要要求是我不希望用户离开当前页面。
I have an url /reportcsv
that generates a plain text csv with Content-type: text/csv
and Content-disposition: attachment; filename=report.csv
. I want trigger this csv to be downloaded using Javascript. I'm considering two methods:
1) Setting location.href = /reportcsv
2) Setting an iframe url to /reportcsv
Both seem to work in Safari. I was wondering if there is any difference between them, or if one is recommended over the other. My main requirement is that I don't want the user to leave the current page.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
只要正确设置
Content-disposition
标头,就应该没问题。在这种情况下,location.href
被认为是最好的方法,因为它更容易,而且应该就像按下载链接一样。此外,如果您的服务器回复文件以外的内容(例如错误代码),用户一定会在 iframe 方法中看到它,他们可以永远等待(假设 iframe 不可见)。You should be fine as long as you're setting the
Content-disposition
header correctly. In that case,location.href
comes to mind as the best way because it's easier and it should be just like pressing a download link. Also if your server replies with something other than the file (such as an error code), users would be sure to see it while in the iframe method they could just stay waiting forever (assuming that the iframe isn't visible).