如何在javascript中从window.open()重命名下载的文件? [英] How to rename downloaded files from window.open() in javascript?

查看:2083
本文介绍了如何在javascript中从window.open()重命名下载的文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近偶然发现此JSFiddle关于如何直接将表转换为Excel 文件花哨的插件.它确实适合我的需要,但是有一个缺陷,我无法重命名其文件. Chrome将文件重命名为download,而Firefox为其随机命名.

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 ?

推荐答案

使用<a>元素和download属性

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/

jsfiddle https://jsfiddle.net/jWAJ7/4549/

这篇关于如何在javascript中从window.open()重命名下载的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆