Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to specify the filename of a data-URI resource in an anchor tag?

I want to implement client side downloadable file using javascript and am using DATA URI to dynamically create the file in client side using following way:

<a href="data:application/csv;charset=utf-8,Col1%2CCol2%2CCol3%0AVal1%2CVal2%2CVal3%0AVal11%2CVal22%2CVal33%0AVal111%2CVal222%2CVal333">Download CSV</a>

However, the downloaded file doesn't have a name. I saw some solutions on stackoverflow where 'download' attribute can be used but I need to support old browsers so I cannot use this.

like image 609
Vinit Sharma Avatar asked Mar 20 '23 12:03

Vinit Sharma


1 Answers

You can easily adapt this piece of code to your needs:

//Generate a file name
    var fileName = "List_";
    //this will remove the blank-spaces from the title and replace it with an underscore
    fileName += ReportTitle.replace(/ /g,"_");   

    //Initialize file format you want csv or xls
    var uri = 'data:text/csv;charset=utf-8,' + escape(CSV);

    // Now the little tricky part.
    // you can use either>> window.open(uri);
    // but this will not work in some browsers
    // or you will not get the correct file extension    

    //this trick will generate a temp <a /> tag
    var link = document.createElement("a");    
    link.href = uri;

    //set the visibility hidden so it will not effect on your web-layout
    link.style = "visibility:hidden";
    link.download = fileName + ".csv";

    //this part will append the anchor tag and remove it after automatic click
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
like image 70
Rafa Avatar answered Apr 06 '23 15:04

Rafa