0

I'm trying to download a file based on a Select object on my web page. I've got the backend stuff taken care of, but am having trouble figuring out get the file to download. I'm using the URL to tell the backend what data to return. My original HTML is this:

<select id="emailListType" class="selectList rpt-status-item" style="display:inline-block">
    <option value="confirmed" selected>Confirmed Emails Only</option>
    <option value="unconfirmed">Unconfirmed Emails Only</option>
    <option value="all">All Emails That We Have</option>
</select>
<button class="rpt-status-item" onclick="generateEmailCSV()">Generate CSV File</button>

where the function being called is:

function generateEmailCSV() {
    // Get the data from the server and fill it in
    var url = "/alumni/reports/emails/" + $('#emailListType').val();
    $.get(url)
    .done(function(data) {
        $('#emailCsvHdr').text('The file should be downloaded.').val();
    })
    .fail(function() {
        console.log("Message post error");
    });
}

How do I indicate that the file should be downloaded as it would be by having 'download' in an anchor tag?

Tom
  • 31
  • 6

1 Answers1

0

Borrowing from owencm's answer here.

The solution is to insert your returned url into a custom function that creates and then calls a link (to your file's URL).

function downloadURI(uri, name) {
    var link = document.createElement("a");
    link.download = name;
    link.href = uri;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    delete link;
}

And then call it in your .done with:

downloadURI(uri, filename);
Ryan Gibbs
  • 1,292
  • 1
  • 15
  • 27