简体   繁体   English

用Javascript下载文本文件

[英]Downloading text file with Javascript

I have been trying to download a text file with javascript. 我一直在尝试使用javascript下载文本文件。 I'm using this code: 我正在使用此代码:

HTML: <a id="save_file_local" download="data.local">Save file</a> HTML: <a id="save_file_local" download="data.local">Save file</a>

Javascript: Javascript:

save_file_local.href="data:text/plain,"+encodeURIComponent(response);
save_file_local.click();    

Well, it works perfect with all extensions I have used.. but only with " .local" extension, I get a file with this name: data.download I really need to download the " .local" file, so to change of extension is not a solution for me. 好吧,它可以与我使用的所有扩展名完美搭配..但是只有使用“ .local”扩展名,我才能得到一个名称为data.download的文件,我真的需要下载“ .local”文件,因此要更改扩展名这不是我的解决方案。 It works perfectly with Internet Explorer 10, but not with Chrome or Mozilla. 它可以与Internet Explorer 10完美配合,但不能与Chrome或Mozilla完美配合。

I have been searching without luck... so Thanks for your help! 我一直在寻找没有运气的东西...谢谢您的帮助!

From an alternate question: 从另一个问题:

<a href="path/to/file" download>Click here to download</a>

Thought no way to do this completely cross browser apparently. 显然没有办法完全跨浏览器来做到这一点。

This depends on your browser and on the Server. 这取决于您的浏览器和服务器。

If a Server sends the "Content-type: text/plain" the most browsers will display it. 如果服务器发送“内容类型:文本/纯文本”,则大多数浏览器将显示它。 Its nothing you can change with javascript. 您可以使用javascript进行更改。

As evu suggested, you could use the HTML5 download attribute, although it isn't widely or consistently supported yet . 如evu所建议的那样,您可以使用HTML5 download属性,尽管该属性尚未得到广泛或一致的支持 Chrome give priority to the download attribute, but Firefox gives priority to the http header Content-Disposition . Chrome优先考虑download属性,而Firefox 优先考虑 http标头Content-Disposition However, if it's content you generated in JavaScript, then the download attribute should work. 但是,如果它是用JavaScript生成的内容,则download属性应该起作用。

If you've got access to the server, setting Content-Disposition: attachment; 如果您有权访问服务器,请设置Content-Disposition: attachment; in your http header would be a much better solution. 在您的http标头中将是一个更好的解决方案。

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

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