我正在尝试创建一个允许用户上传图像并使用React和Firebase在页面中显示图像的应用程序。
这是导致问题的代码部分: 图片变量来自状态
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)
,但没有用
答案 0 :(得分:1)
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
创建更多有关模板文字的引用here
image
变量的内容,我从代码中可以看到,您正在一个似乎是回调的函数中调用setState
,但是我看不到您从哪里打来,您可以通过这样的输入来做到这一点:<input type="file" onChange={handleChange} />
如果您已经这样使用它,建议将console.log(image)
添加到函数外部,以便在将变量发送到put()
之前调试变量的内容。就像参考一样,console.log(image)
的输出应该是File
javascript API