最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - how to specify csv file name for downloading in window.location.href - Stack Overflow

programmeradmin3浏览0评论

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?

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?

Share Improve this question edited Oct 16, 2015 at 23:25 WABBIT0111 asked Oct 16, 2015 at 23:09 WABBIT0111WABBIT0111 2,3134 gold badges20 silver badges30 bronze badges 1
  • FYI, i am using Angular. with ng-click to trigger a function. due to some aspect, i would not and cannot create a <a> tag in place. thus would there be another way to just specify in window.location.href to specify the filename? – WABBIT0111 Commented Oct 16, 2015 at 23:25
Add a ment  | 

1 Answer 1

Reset to default 12

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;

发布评论

评论列表(0)

  1. 暂无评论