6

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?

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

As this has to work in IE is my best option then to have the backend return the entire file thereby defining the filename?
indeed, IE doesn't support this, so yes, the option is to solve it from the backend

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.