Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 901
WABBIT0111 Avatar asked Oct 16 '15 23:10

WABBIT0111


People also ask

How do you pass data using Windows location href?

Using window. location. href it's not possible to send a POST request. What you have to do is to set up a form tag with data fields in it, set the action attribute of the form to the URL and the method attribute to POST, then call the submit method on the form tag.

How do I change the name of a file open in Windows?

Open File Explorer by going to My Computer, or by pressing Windows Key + E on your keyboard. Find the file you want to rename, select it and select Rename on the ribbon (or press F2 on your keyboard). Type the new name you want the file to have and press Enter.

What does setting window location href do?

The location. href property sets or returns the entire URL of the current page.


1 Answers

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;
like image 197
Axel Amthor Avatar answered Oct 13 '22 00:10

Axel Amthor