我正在尝试让用户从firebase存储中下载图像。每个图像都有它的下载url保存在一个firestore集合中,所以当生成图像时,每个都会被分配到它的正确URL。像这样:
<img src="https://firebasestorage.googleapis.com/v0/b/odyssey-
f90f0.appspot.com/o/images%2F2539888b-eabd-84b9-9c72-b0f1ee9b0af6?alt=media&token=acb8655f-fd8f-
4d94-9ba0-dc29c3f3c399">它可以很好地实际获取和显示图像。但是,当我尝试让用户使用另一个带有下载属性的链接下载它时:
<a href="#" download="https://firebasestorage.googleapis.com/v0/b/odyssey-
f90f0.appspot.com/o/images%2F2539888b-eabd-84b9-9c72-b0f1ee9b0af6?
alt=media&token=acb8655f-fd8f-4d94-9ba0-dc29c3f3c399">Download</a>它只是下载一些奇怪的文件格式,这些文件是不可见的:
最初我只是认为这是CORS问题,所以我按照firebase文档https://firebase.google.com/docs/storage/web/download-files下载了gsutil命令行工具,然后设置cors.json并设置CORS确认,如下所示:
[
{
"origin": ["*"],
"method": ["GET"],
"maxAgeSeconds": 3600
}
]从那时起,它仍然不起作用,所以我将谷歌云图像存储桶上的读取设置为公共,并确保我的firebase存储规则也设置为公共读取。仍然没有变化。
在这一点上,我真的不知道该怎么办。也许有一些方法可以使用这段代码(关于如何下载文件的firebase文档)来获取实际的文件数据,并将其设置为download属性,而不是url或其他什么,但我不知道该怎么做。
function downloadImage(imageURL) {
// Create a reference to the file we want to download
var httpsReference = storage.refFromURL(imageURL);
// Get the download URL
httpsReference.getDownloadURL()
.then((url) => {
// download image directly via url
var xhr = new XMLHttpRequest();
xhr.responseType = 'blob';
xhr.onload = (event) => {
var blob = xhr.response;
};
xhr.open('GET', url);
xhr.send();
});此外,奇怪的是-如果我右键单击网站上显示的图像,另存为-然后手动设置.jpg或.png文件扩展名或它下载并工作的东西。然而,当我将其添加到代码中时,它只是下载了一个“不受支持的格式”的文件。
任何帮助,甚至是我错过的参考资料,我都将不胜感激。
发布于 2021-04-02 06:28:28
我想出了一个变通办法。
<body>
<a id = 'tagID' href = '' download = ''>Download</a>
</body>
<script>
//create a reference to the image in the firebase storage by using the url
var httpsReference = storage.refFromURL(imageURL);
// Get the download URL
httpsReference.getDownloadURL()
.then((url) => {
// download image directly via url
var xhr = new XMLHttpRequest();
xhr.responseType = 'blob';
xhr.onload = (event) => {
var blob = xhr.response;
//create a file from the returned blob
var file = new File([blob], "image name", { type: blob.type });
//grab the a tag
a1 = document.getElementById('tagID');
//set the download attribute of the a tag to the name stored in the file
a1.download = file.name;
//generate a temp url to host the image for download
a1.href = URL.createObjectURL(file);
};
xhr.open('GET', url);
xhr.send();
});
</script>现在,当用户单击锚点元素时,将会下载图像。
注意:您可以使用直接路径或指向google cloud的url创建对存储的引用。请参阅firebase文档:https://firebase.google.com/docs/storage/web/download-files
https://stackoverflow.com/questions/66911265
复制相似问题