[英]Async/Await: "out of range error" when trying to access array filled with downloaded images from firebase storage
[英]Error when trying to upload images to Firebase storage
我正在嘗試創建一個應用程序,允許用戶上傳圖像並使用 React 和 Firebase 在頁面中顯示它。
這是導致問題的代碼部分:圖像變量來自 state
const [image, setImage] = useState("");
const [caption, setCaption] = useState("");
const [progress, setProgress] = useState(0)
function handleChange (e){
if (e.target.files[0]){
setImage(e.target.files[0]);
}
}
function handleUpload(){
const uploadTask = storage.ref('images/${image.name}').put(image)
uploadTask.on(
"state_changed",
(snapshot) => {
const progress = Math.round(
(snapshot.bytesTransferred / snapshot.totalBytes) * 100
);
setProgress(progress);
},
(error) => {
console.log(error);
alert(error.message);
},
() => {
storage
.ref("images")
.child(image.name)
.getDownloadURL()
.then(url => {
db.collection("posts").add({
timestamp: db.FieldValue.serverTimestamp(),
caption : caption,
imgUrl: url,
userName: username
})
setProgress(0);
setCaption("");
setImage(null);
})
}
)
}
並且此錯誤記錄在控制台中:
Uncaught
FirebaseStorageError {code_: "storage/invalid-argument", message_: "Firebase Storage: Invalid argument in `put` at index 0: Expected Blob or File.", serverResponse_: null, name_: "FirebaseError"}code_: "storage/invalid-argument"message_: "Firebase Storage: Invalid argument in `put` at index 0: Expected Blob or File."name_: "FirebaseError"serverResponse_: nullcode: (...)message: (...)name: (...)serverResponse: (...)__proto__: Object
rethrowCaughtError @ react-dom.development.js:328
runEventsInBatch @ react-dom.development.js:3336
runExtractedPluginEventsInBatch @ react-dom.development.js:3537
handleTopLevel @ react-dom.development.js:3581
batchedEventUpdates$1 @ react-dom.development.js:21729
batchedEventUpdates @ react-dom.development.js:798
dispatchEventForLegacyPluginEventSystem @ react-dom.development.js:3591
attemptToDispatchEvent @ react-dom.development.js:4311
dispatchEvent @ react-dom.development.js:4232
unstable_runWithPriority @ scheduler.development.js:659
runWithPriority$1 @ react-dom.development.js:11077
discreteUpdates$1 @ react-dom.development.js:21746
discreteUpdates @ react-dom.development.js:811
dispatchDiscreteEvent @ react-dom.development.js:4211
我試圖將put(image)
更改為put(blob)
但它沒有用
const uploadTask = storage.ref('images/${image.name}').put(image)
有錯誤,它應該使用符號`
(反引號/反引號)而不是使用單引號'
:
const uploadTask = storage.ref(`images/${image.name}`).put(image)
否則,您將創建對文字字符串images/${image.name}
的引用,而不是image/value_of_variable_image.jpg
可以在此處找到有關模板文字的更多信息
image
變量的內容是什么,我從代碼中可以看出你在 function 中調用了一個setState
似乎是一個回調,但我沒有看到你在哪里調用,你可以從這樣的輸入中做到這一點:<input type="file" onChange={handleChange} />
如果您已經在使用它,我建議在 function 之外添加console.log(image)
以便在將變量發送到put()
之前調試變量的內容。 作為參考,來自console.log(image)
的 output 應該是File
javascript API的一個實例
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.