javascript javascript文件下载

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11834019/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 14:29:35  来源:igfitidea点击:

javascript file download

javascriptjqueryhtml

提问by User

I need to download a file (test.xml) and allow/prompt user to save the file on click on download button. The file resides in url "http://localhost/test/test.xml" .

我需要下载一个文件 (test.xml) 并允许/提示用户点击下载按钮保存文件。该文件位于 url "http://localhost/test/test.xml" 中。

I have added html code

我已经添加了 html 代码

<input type=button value="Download" onclick='javascript:download()/>

and javascript code is

和 javascript 代码是

function download() {
   var url = "http://localhost/test/test.xml";
       window.open(url, 'Download');
}

But this opens the page in new window. How do I prompt to download and save the file. Any inputs will be of help. Thanks

但这会在新窗口中打开页面。如何提示下载并保存文件。任何输入都会有所帮助。谢谢

回答by Simon Edstr?m

You have to change the content type in the header. You need to do some server scripting or configurate your webserver.

您必须更改标题中的内容类型。您需要编写一些服务器脚本或配置您的网络服务器。

I Googled a link that will help you in the right direction: http://www.boutell.com/newfaq/creating/forcedownload.html

我在谷歌上搜索了一个可以帮助您朝着正确方向前进的链接:http: //www.boutell.com/newfaq/creating/forcedownload.html

回答by SReject

Using you inital code, if you have access to the backend, when the xml is requested, add the following header with it:

使用您的初始代码,如果您有权访问后端,则在请求 xml 时,添加以下标头:

Content-disposition: attachment; filename=test.xml;

Another route would be to use xmlhttprequest to get the file, then use a flash plugin to save it. I've used this method a bit, and the flash swf can be found here

另一种方法是使用 xmlhttprequest 来获取文件,然后使用 flash 插件来保存它。我已经使用过这种方法了,可以在这里找到 flash swf

回答by Prog Mania

set the content type for the response header of the xml to be application/xml

将 xml 响应头的内容类型设置为 application/xml

回答by Vikram

html:

html:

<input id="downloadthis" value="Download"/>

inside javascript tag:

在 javascript 标签中:

  $('#downloadthis').click( function() {
window.location.href = 'http://localhost/test/test.xml';
 } );

REF: https://stackoverflow.com/a/4864264/405117

参考资料:https: //stackoverflow.com/a/4864264/405117