Browser download file prompt using JavaScript

时光总嘲笑我的痴心妄想 提交于 2019-11-27 07:38:58

问题


I was wondering if there was any method to implement browser's download file prompt using JavaScript.

My reason - well users will be uploading files to a local fileserver which cannot be accessed from the webserver. In other words, both will be on different domains!

For example, let’s say websites hosted on www.xyz.com, but files would reside on local file server with address like \\10.10.10.01\Files\file.txt. How am I uploading/transferring file to local fileserver... using ActiveX and VBscript! (don’t ask :-)

So I am storing local file path in my database and binding that data to a grid. When the user clicks on that link, the file opens in a window (using JavaScript).

Problem is certain file types like text, jpg, pdf, etc. open inside browser window. How would I be able to implement content-type or content-disposition using client side scripting? Is that even possible?

EDIT: the local file server has a window's shared folder on which the files are saved.


回答1:


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




回答2:


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.




回答3:


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




回答4:


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



来源:https://stackoverflow.com/questions/727144/browser-download-file-prompt-using-javascript

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