首页 > 解决方案 > 如何在前端指定下载文件名

问题描述

更新:

在 JavaScript 中从 base64 字符串创建 Blob

我正在尝试实现单击按钮并从其 DataURL 下载文件。

目前,由于 Chrome 已经限制了旧的方式,例如构建<a>链接,它会抛出如下错误:

不允许将顶部框架导航到数据 URL:....

我找到的解决方案是使用 iframe 打开新窗口并将 DataURL 设置为其src

let jpgWindow = window.open("", "_blank")
var html = "<html><body><iframe width='100%' height='100%' src='data:application/jpeg;base64, "+ theDataURL+"'></iframe></body></html>";
jpgWindow.document.write(html)

当我单击按钮时,下载工作,但图片以文件名“下载”下载,我无法指定我希望它默认的文件名。

任何想法?

标签: javascript

解决方案


查看window.URL.createObjectURL https://developer.mozilla.org/en-US/docs/Web/API/URL/createObjectURL

const blob = new Blob(['array of data in your file'], {type : 'text/rtf'});
const anchor = document.createElement('a');

anchor.href = window.URL.createObjectURL(blob);
anchor.download = 'the-file-name.txt';
anchor.click();

推荐阅读