Browser download file prompt using JavaScript

痞子三分冷 提交于 2019-11-28 13:24:21
John Gietzen

"content-disposition: attachment" is pretty much the only way to force that, and this MUST be set in the response header.

If the file is hosted on a web server like in your example, you can do:

window.location.replace(fileUrl);

.. and the browser will figure out what to do with the file. This works great for most files, such as .xls, .csv, etc, but keep in mind that this isn't full-proof because the user's MIME handler settings will determine what to do with the file... i.e. if it is a .txt file it will most likely just be displayed in the browser and will not be given a "file download" dialogue box.

As of August 2015, adding the "download" attribute to your tag enables the behavior you're looking for, at least in Chrome.

You could try using a plain hyperlink with type="application/octet-stream". Seems to work in FF, but IE and Opera ignore the attribute.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!