[英]How to upload SVG images on firebase storage?
I am having issue to upload an SVG image to firebase storage.我在将 SVG 图像上传到 firebase 存储时遇到问题。 The upload seems to work correctly how when I am trying to click on the link.当我尝试单击链接时,上传似乎可以正常工作。 It returns the error file empty as per screenshot below.它按照下面的屏幕截图返回空的错误文件。
Please see below my upload function请看下面我上传的function
import { getStorage, ref, uploadBytesResumable, getDownloadURL } from "firebase/storage"
export const uploadToFirebase = async (file) => {
const storage = getStorage()
const storageRef = ref(storage, "images/avatar.svg")
const metadata = {
contentType: "image/svg+xml",
}
const uploadTask = uploadBytesResumable(storageRef, file, metadata)
uploadTask.on(
"state_changed",
(snapshot) => {
const progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100
console.log("Upload is " + progress + "% done")
switch (snapshot.state) {
case "paused":
console.log("Upload is paused")
break
case "running":
console.log("Upload is running")
break
}
},
(error) => {
// A full list of error codes is available at
// https://firebase.google.com/docs/storage/web/handle-errors
switch (error.code) {
case "storage/unauthorized":
// User doesn't have permission to access the object
break
case "storage/canceled":
// User canceled the upload
break
// ...
case "storage/unknown":
// Unknown error occurred, inspect error.serverResponse
break
}
},
() => {
// Upload completed successfully, now we can get the download URL
getDownloadURL(uploadTask.snapshot.ref).then((downloadURL) => {
console.log("File available at", downloadURL)
})
}
)
}
i am calling this function in my home component as fellow我在我的家庭组件中称这个 function 作为伙伴
useEffect(() => {
uploadToFirebase("../public/avatar.svg")
}, [])
Can someone help me underytand what is wrong with my code,please?有人可以帮我理解我的代码有什么问题吗?
You pass a String to your uploadToFirebase()
method which results in calling the uploadBytesResumable()
method with a String as second argument.您将一个字符串传递给您的uploadToFirebase()
方法,这会导致使用一个字符串作为第二个参数调用uploadBytesResumable()
方法。
As explained in the doc (above link), this second argument shall be a Blob, a Uint8Array or an ArrayBuffer.如文档(上方链接)中所述,第二个参数应为 Blob、Uint8Array 或 ArrayBuffer。
Following our below comments: I'm not verse in reactjs but you need to get the image from your public folder as a Blob
Object (or as a File
Object, which is "a specific kind of Blob" ) and pass it to your uploadToFirebase()
method.按照我们的以下评论:我不是 reactjs 中的诗句,但您需要从公共文件夹中获取图像作为Blob
Object(或作为File
Object,这是“一种特定类型的 Blob” )并将其传递给您的uploadToFirebase()
方法。 The following SO question & answers give several ways to do that (untested).以下SO 问题和答案提供了几种方法(未经测试)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.