Skip to content
Advertisement

How do I write inta a file and download the file using Javascript?

A file is getting uploaded to a remote server and I need to download the file to the local machine. Im running a GET call through ajax to get the data. On running the following code –

JavaScript

This line returns the contents of the file in the console in the browser. I need to write this data into a file and then download the file using Javascript. The file can be in any format like txt, pdf, png,jpg etc. Is there also a way to handle all different file formats in one way? My first priority though is txt file. How can i do that?

Any help would be appreciated. Thank you.

Advertisement

Answer

Ideally you can do this simply by using data URIs. Creating a <a> tag and providing a blob into href attribute of the tag.

<a href="data:application/octet-stream;charset=UTF-8;base64,//VGV4dCBmaW5sZSBleGFtcGxl">Link to download text file</a>

But if you want it to be downloaded by a script, you can create an <a> tag and click on it programatically and delete the <a> tag.

Please try the below code in browser console. As the Run code snippet button seems to not work for some reason.

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement