根据EJS

时间:2018-06-11 22:39:02

标签: javascript ejs

我正在尝试根据网页上的Select对象下载文件。我有后端的东西照顾,但我很难搞清楚得到文件下载。我正在使用URL告诉后端要返回的数据。我的原始HTML是:

<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>

其中被调用的函数是:

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");
    });
}

如何通过在锚标记中“下载”来指示应该下载文件?

1 个答案:

答案 0 :(得分:0)

借用owencm的答案here.

解决方案是将您返回的网址插入到自定义函数中,该函数会创建并调用链接(到您文件的网址)。

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;
}

然后在.done中使用:

调用它
downloadURI(uri, filename);