问题描述
我需要下载一个文件(test.xml)并允许/提示用户在点击下载按钮时保存文件。该文件位于URLhttp://localhost/test/test.xml。
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" .
我添加了html代码
<input type=button value="Download" onclick='javascript:download()/>
和javascript代码是
and javascript code is
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
推荐答案
使用初始代码,如果您有权访问后端,请求xml时,添加以下标题它:
Using you inital code, if you have access to the backend, when the xml is requested, add the following header with it:
Content-disposition: attachment; filename=test.xml;
另一种方法是使用xmlhttprequest获取文件,然后使用flash插件保存它。我已经使用过这种方法,可以在找到flash swf。
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
这篇关于javascript文件下载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!