how to specify csv file name for downloading in window.location.href

All we need is an easy explanation of the problem, so here it is.

I am exporting data using javascript to csv. for some reason i am not allowed to use the traditional
<a download="filename.csv" /a>
to set the file name.

I have the following line of code:

window.location.href = "data:text/csv;base64," + csvdata

Where and how can i insert and specify the file name and extension to make it work?

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

It’s not possible that way, try to emulate the <a href=.. with a click on it like this:

        var csvdata = "Hello World"; //  only for test
        var byteNumbers = new Uint8Array(csvdata.length);

		for (var i = 0; i < csvdata.length; i++)
		{
			byteNumbers[i] = csvdata.charCodeAt(i);
		}
		var blob = new Blob([byteNumbers], {type: "text/csv"});
   
        // Construct the uri
		var uri = URL.createObjectURL(blob);

		// Construct the <a> element
		var link = document.createElement("a");
		link.download = 'myfile.csv';
		link.href = uri;

		document.body.appendChild(link);
		link.click();

		// Cleanup the DOM
		document.body.removeChild(link);
		delete link;

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply