Browser download file prompt using JavaScript

2019-01-20 08:34发布

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.

4条回答
神经病院院长
2楼-- · 2019-01-20 08:49

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

查看更多
我想做一个坏孩纸
3楼-- · 2019-01-20 08:54

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

查看更多
放荡不羁爱自由
4楼-- · 2019-01-20 08:58

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

查看更多
手持菜刀,她持情操
5楼-- · 2019-01-20 09:00

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.

查看更多
登录 后发表回答