简体   繁体   English

浏览器使用JavaScript下载文件提示

[英]Browser download file prompt using JavaScript

I was wondering if there was any method to implement browser's download file prompt using JavaScript. 我想知道是否有任何方法可以使用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 . 例如,假设网站托管在www.xyz.com ,但文件将驻留在本地文件服务器上,其地址类似于\\\\10.10.10.01\\Files\\file.txt How am I uploading/transferring file to local fileserver... using ActiveX and VBscript! 如何使用ActiveX和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). 当用户单击该链接时,该文件将在窗口中打开(使用JavaScript)。

Problem is certain file types like text, jpg, pdf, etc. open inside browser window. 问题是在浏览器窗口内打开文本,jpg,pdf等特定文件类型。 How would I be able to implement content-type or content-disposition using client side scripting? 如何使用客户端脚本实现content-typecontent-disposition Is that even possible? 这甚至可能吗?

EDIT: the local file server has a window's shared folder on which the files are saved. 编辑:本地文件服务器有一个窗口的共享文件夹,文件保存在该文件夹中。

“content-disposition:attachment”几乎是强制它的唯一方法,这必须在响应头中设置。

自2015年8月起,向您的代码添加“下载”属性可启用您正在寻找的行为,至少在Chrome中是这样。

If the file is hosted on a web server like in your example, you can do: 如果文件托管在Web服务器上(如示例所示),则可以执行以下操作:

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... ie 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. 这适用于大多数文件,例如.xls,.csv等,但请记住,这不是完全证明,因为用户的MIME处理程序设置将决定如何处理文件...即如果是一个.txt文件很可能只是在浏览器中显示,并且不会给出“文件下载”对话框。

You could try using a plain hyperlink with type="application/octet-stream" . 您可以尝试使用type="application/octet-stream"的普通超链接。 Seems to work in FF, but IE and Opera ignore the attribute. 似乎在FF中工作,但IE和Opera忽略该属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM