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 -
console.log(xhrdoc.responseText);
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.
CodePudding user response:
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-16le;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.
function downloadFileWithContents(filename, fileContents) {
const blob = new Blob([fileContents], {type: 'text'}); // create a blob with fileContents
if(window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveBlob(blob, filename);
}
else{
const elem = window.document.createElement('a');
elem.href = window.URL.createObjectURL(blob);
elem.download = filename;
document.body.appendChild(elem);
elem.click();
document.body.removeChild(elem);
}
}
downloadFileWithContents('Filename.txt', 'TEXT');
// downloadFileWithContents('Filename.txt', xhrdoc.responseText)