如何使用 NextJs 从 firebase 存储中下载图像?怎么解决这个问题?

问题描述 投票:0回答:1

我们使用以下代码在 Nextjs 中下载图像

       const handleDownload = async (fileUrl: string) => { try { const storageRef = ref(storage, fileUrl); 
const downloadURL = await getDownloadURL(storageRef);
        const downloadLink = document.createElement("a");
        downloadLink.href = downloadURL;
        downloadLink.target = "_blank";
        downloadLink.download = "file_name.ext"; // Set the desired file name
        downloadLink.textContent = "Download File";
        document.body.appendChild(downloadLink);
        downloadLink.click();
    } catch (error) {
        // Handle any errors that occurred during the download
        console.error("Error downloading file:", error);
    }
};
firebase next.js firestorter
1个回答
1
投票

您需要创建对存储中的文件的引用:

const storage = getStorage()
const ref = ref(storage, 'path/to/image.ext')
const url = await getDownloadURL(ref)

然后,如果你想下载图像,你可以使用

XMLHttpRequest
axios
或任何其他类似的库来获取下载网址:

const xhr = new XMLHttpRequest();
xhr.responseType = 'blob';
xhr.onload = (event) => {
  const blob = xhr.response;
};
xhr.open('GET', url);
xhr.send();

或者,如果您想显示图像,您可以创建一个新的

img
标签:

const img = document.createElement('img');
img.setAttribute('src', url);

您可以在此处

了解有关从 Firebase 存储下载文件的更多信息
© www.soinside.com 2019 - 2024. All rights reserved.