I am writing JavaScript code to initiate a download of a file in the browser. I am able to get the bytes of the file in a string and I want to pass the string to a function that creates a file and initiates a download from it.
I have to avoid just storing the file on the server for someone to download through html like:
<a href="./some-file.pdf">file</a>
Here is the code I have so far which works just fine, but I need to modify the extension of the file to change it to match the data, which is the part I havn't figured out.
function download(data, filename = "aserc", type = ".txt") {
var file = new Blob([data], {type: type});
if (window.navigator.msSaveOrOpenBlob)
{
window.navigator.msSaveOrOpenBlob(file, filename);
} else {
var a = document.createElement("a"), url = URL.createObjectURL(file);
a.href = url;
a.download = filename;
document.body.appendChild(a);
a.click();
setTimeout(() => {
document.body.removeChild(a);
window.URL.revokeObjectURL(url);
}, 0);
}
}
this will download a file but it will not be a .txt file. How do I change the type of the file using this code?
text/plainperhaps?, not a file extension ... filename should beaserc.txta.download = filename + typeand add the required headerapplication/octet-stream