使用jquery下载文件自定义名称

我使用jQuery 插件将HTML表导出到Excel。 使用chrome下载的文件名总是download.xls并使用mozilla firefox,它是random-string.xls 。 我希望根据日期创建文件名。 例如23-06-2014.xls

下面是视图文件中的自定义JS块

 $(document).ready(function () { $("#btnExport").click(function () { $("#account_table").btechco_excelexport({ containerid: "account_table", datatype: $datatype.Table }); }); }); 

您想在链接上设置downloadhref属性。 例如

 $("#btnExport").click(function () { var uri = $("#account_table").btechco_excelexport({ containerid: "account_table", datatype: $datatype.Table, returnUri: true }); $(this).attr('download', 'ExportToExcel.xls') // set file name (you want to put formatted date here) .attr('href', uri) // data to download .attr('target', '_blank') // open in new window (optional) ; }); 

如果您不想使用此插件,那么人们已经编写了另一种JavaScript。 我只是将其修改为具有文件名而不是默认名称。

 var tableToExcel = (function () { var uri = 'data:application/vnd.ms-excel;base64,', template = '{table}
', base64 = function (s) { return window.btoa(unescape(encodeURIComponent(s))) }, format = function (s, c) { return s.replace(/{(\w+)}/g, function (m, p) { return c[p]; }) } return function (table, name) { if (!table.nodeType) table = document.getElementById(table) var ctx = { worksheet: name || 'Worksheet', table: table.innerHTML } var blob = new Blob([format(template, ctx)]); var blobURL = window.URL.createObjectURL(blob); return blobURL; } })()

设置名称的jquery将是:

 $("#btnExport").click(function () { var todaysDate = moment().format('DD-MM-YYYY'); var blobURL = tableToExcel('account_table', 'test_table'); $(this).attr('download',todaysDate+'.xls') $(this).attr('href',blobURL); }); 

示例: 小提琴

参考文献: Link1 Link2