我们使用以下代码在 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";
// Set the desired file name
downloadLink.download = "file_name.ext";
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);
}
};
如何解决这个问题?
您需要创建对存储中的文件的引用:
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 存储下载文件的更多信息