Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to rename downloaded files from window.open() in javascript?

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 ?

like image 308
DennyHiu Avatar asked Sep 18 '25 17:09

DennyHiu


1 Answers

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.net/jWAJ7/4549/

like image 67
guest271314 Avatar answered Sep 21 '25 09:09

guest271314