![](/img/trans.png)
[英]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.