gpt4 book ai didi

javascript - 如何在FrontEnd中指定下载文件名

转载 作者:行者123 更新时间:2023-11-30 14:30:49 24 4
gpt4 key购买 nike

更新:

Creating a Blob from a base64 string in JavaScript

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

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

Not allowed to navigate top frame to data 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();

关于javascript - 如何在FrontEnd中指定下载文件名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51199879/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com