生成blob地址后可以调用window.open来下载吗
- User
生成blob地址后可以调用window.open来下载吗
Assistant
在大多数情况下,使用
window.open来下载Blob URL并不可靠,因为不同浏览器的行为不同。更推荐的方法是使用标签来触发下载。以下是一个示例代码:const blob = new Blob(['Hello, world!'], { type: 'text/plain' }); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = 'hello.txt'; a.click(); URL.revokeObjectURL(url);这样,无论在哪个浏览器中,都能可靠地触发文件下载。如果你仍然希望使用
window.open,可以尝试以下代码:const blob = new Blob(['Hello, world!'], { type: 'text/plain' }); const url = URL.createObjectURL(blob); window.open(url);但是,请注意,这种方式在大多数浏览器中可能不会触发下载,而是会在新标签页中显示Blob内容。因此,更推荐使用标签的方法。
如果你有更具体的需求或遇到问题,请提供更多细节,我可以帮助你进一步优化解决方案。
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.