javascript - 如何在前端指定下载文件名
问题描述
更新:
在 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)
当我单击按钮时,下载工作,但图片以文件名“下载”下载,我无法指定我希望它默认的文件名。
任何想法?
解决方案
查看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();
推荐阅读
- json - 有没有办法使用 ruby 和位置直接转到 JSON 节点?
- javascript - android studio webview 使用 javascript 作为链接
- java - 使用 java 11 设置电子邮件
- python - 在 quip 中自动插入一个 python 数据框
- python - Bash 脚本 - Python 找不到路径
- javascript - 用 selenium / VBA 改变值
- wkhtmltopdf - 为什么我的标题最终会出现在 TuesPechkin 页面之外?
- amazon-web-services - 使用 DynamoDB Stream 的新数据聚合
- vb.net - DataGrid 格式单元格属性
- javascript - MongoDb 多集合事务不起作用