最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - How to rename downloaded files from window.open() in javascript? - Stack Overflow

programmeradmin2浏览0评论

I recently stumbled upon this JSFiddle about how to convert a table to Excel file directly without any fancy plugins. It really suits my need, but it has a flaw, I can't rename its file. Chrome renames the file to download and Firefox gives a random name to it.

$("#btnExport").click(function (e) {
    window.title = "filename.xls"; // this part doesn't work
    window.open('data:application/vnd.ms-excel,' +     
    $('#dvData').html());
    e.preventDefault();
});

How can I rename the downloaded file ?

I recently stumbled upon this JSFiddle about how to convert a table to Excel file directly without any fancy plugins. It really suits my need, but it has a flaw, I can't rename its file. Chrome renames the file to download and Firefox gives a random name to it.

$("#btnExport").click(function (e) {
    window.title = "filename.xls"; // this part doesn't work
    window.open('data:application/vnd.ms-excel,' +     
    $('#dvData').html());
    e.preventDefault();
});

How can I rename the downloaded file ?

Share Improve this question asked Jan 31, 2017 at 2:04 DennyHiuDennyHiu 6,13010 gold badges57 silver badges93 bronze badges 0
Add a ment  | 

1 Answer 1

Reset to default 2

Use <a> element with download attribute

let file = new Blob([$('#dvData').html()], {type:"application/vnd.ms-excel"});

let url = URL.createObjectURL(file);

let a = $("<a />", {
  href: url,
  download: "filename.xlsx"
})
.appendTo("body")
.get(0)
.click();

jsfiddle https://jsfiddle/jWAJ7/4549/

发布评论

评论列表(0)

  1. 暂无评论