Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set filename when downloading a file through javascript

I've taken over the following snippet:

            $.ajax({
                contentType: 'application/json; charset=utf-8',
                type: 'POST',
                url: '/api/generalapi/generatecsv',
                data: data,
                success: function (response) {
                    window.open("data:text/csv;base64," + response, '', '');
                }
            });

I've tried adding

filename=orders.csv

to the window.open but the file still always comes down as "download". No extension or anything.

Is there any way of controlling the filename using the above code?

like image 912
CJe Avatar asked Nov 09 '22 15:11

CJe


1 Answers

try with something like this:

function saveContent(fileContents, fileName)
{
    var link = document.createElement('a');
    link.download = fileName;
    link.href = 'data:,' + fileContents;
    link.click();
}

    $.ajax({
        contentType: 'application/json; charset=utf-8',
        type: 'POST',
        url: '/api/generalapi/generatecsv',
        data: data,
        success: function (response) {
            saveContent("text/csv;base64," + response, 'orders.csv');
        }
    });

The key part is link.download = fileName;, which adds the HTML5 download attribute to the dynamically created link used for the download.

like image 96
Tudor Constantin Avatar answered Nov 15 '22 12:11

Tudor Constantin