JavaScript文件下载

javascript file download

本文关键字:文件下载 JavaScript      更新时间:2023-09-26

我需要下载一个文件(test.xml)并允许/提示用户在单击下载按钮时保存文件。该文件驻留在网址"http://localhost/test/test.xml"中。

我添加了 html 代码

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

JavaScript代码是

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

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

您必须更改标题中的内容类型。您需要执行一些服务器脚本或配置Web服务器。

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

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

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

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

设置要application/xml的 xml 响应标头的内容类型

html:

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

在JavaScript标签中:

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

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