简体   繁体   中英

Downloading text file with Javascript

I have been trying to download a text file with javascript. I'm using this code:

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

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. It works perfectly with Internet Explorer 10, but not with Chrome or 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.

As evu suggested, you could use the HTML5 download attribute, although it isn't widely or consistently supported yet . Chrome give priority to the download attribute, but Firefox gives priority to the http header Content-Disposition . However, if it's content you generated in JavaScript, then the download attribute should work.

If you've got access to the server, setting Content-Disposition: attachment; in your http header would be a much better solution.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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