【发布时间】:2022-01-02 15:29:01
【问题描述】:
我正在尝试在将下载图像的图像上实现下载按钮。由于图像托管在 Firebase 存储上,因此我使用他们的代码变体来检索我在官方文档中找到的文件:https://firebase.google.com/docs/storage/web/download-files#download_data_via_url
我对其进行了一些更改,因为在示例中,代码正在从存储桶上的路径中检索文件 url,而在我的情况下,我已经知道该 url:
download(url) {
const xhr = new XMLHttpRequest();
xhr.responseType = "blob";
xhr.onload = () => {
xhr.response;
};
xhr.open("GET", url);
xhr.send();
},
现在的问题是请求获取的图像但没有触发下载(到用户的机器):
我知道我真的很接近,我如何触发图片下载?此外,由于图像已经显示在网站上,我真的需要从 firebase 调用它吗?
解决方案:
感谢 Renaud 的帮助,我能够修复我的代码:
download(url) {
const xhr = new XMLHttpRequest();
xhr.responseType = "blob";
xhr.onload = () => {
var urlCreator = window.URL || window.webkitURL;
var imageUrl = urlCreator.createObjectURL(xhr.response);
const link = document.createElement("a");
link.href = imageUrl;
link.setAttribute("download", "test");
link.setAttribute("target", "new");
document.body.appendChild(link);
link.click();
};
xhr.open("GET", url);
xhr.send();
},
请随时发布对此解决方案的优化。
【问题讨论】:
标签: firebase vue.js download google-cloud-storage firebase-storage