将图像从 ReactJS 上传到 Firebase v9 存储
Posted
技术标签:
【中文标题】将图像从 ReactJS 上传到 Firebase v9 存储【英文标题】:Upload image from ReactJS to Firebase v9 Storage 【发布时间】:2021-12-31 04:20:36 【问题描述】:我遇到了问题。我想创建一个简单的图像上传输入,并且图像应该存储在 Firebase 存储中。我想我混淆了一些 v8 和 v9 代码,但我也找不到正确的答案。
当我触发上传时,我收到以下错误消息:
TypeError: _firebase_firebase__WEBPACK_IMPORTED_MODULE_1__.storage.ref is not a function
61 |
62 | const uploadFiles = () =>
63 | //
> 64 | const uploadTask = storage.ref(`images/$img.name`).put(img);
| ^ 65 | uploadTask.on(
66 | "state_changed",
67 | (snapshot) =>
这是我正在运行的代码:
import React, useState from "react";
import storage from "../../firebase/firebase";
import ActionBtn, Topbar, SubjectHead, CardList from "../../components/styles";
const CreateImg = () =>
const [img, setImg] = useState(null);
const [progress, setProgress] = useState(0);
const formHandler = (e) =>
e.preventDefault();
const file = e.target.files[0];
setImg(file);
;
const uploadFiles = () =>
const uploadTask = storage.ref(`images/$img.name`).put(img);
uploadTask.on(
"state_changed",
(snapshot) =>
const prog = Math.round(
(snapshot.bytesTransferred / snapshot.totalBytes) * 100
);
setProgress(prog);
,
(error) => console.log(error),
() =>
storage
.ref("images")
.child(img.name)
.getDownloadURL()
.then((url) =>
console.log(url);
);
);
;
return (
<div>
<Topbar>
<SubjectHead>Create New CV</SubjectHead>
<ActionBtn onClick=createCv>Create CV</ActionBtn>
</Topbar>
<CardList type="form">
<div>
<div>
<input
type="file"
accept=".jpg,.png,.jpeg"
onChange=formHandler
/>
<button type="button" onClick=uploadFiles>
Upload
</button>
<h4>progress%</h4>
</div>
</CardList>
</div>
);
;
export default CreateImg;
这是我的配置文件:
import initializeApp from "firebase/app";
import getStorage from "firebase/storage";
const firebaseConfig =
apiKey: "XXX",
authDomain: "XXX",
projectId: "XXX",
storageBucket: "XXX",
messagingSenderId: "XXX",
appId: "XXX",
;
const app = initializeApp(firebaseConfig);
const storage = getStorage(app);
export storage ;
如果有人可以帮助我解决我的问题,我会非常高兴。
【问题讨论】:
import storage from "../../firebase/firebase";
正确吗?
【参考方案1】:
您的进口:
import getStorage, ref from "firebase/storage";
然后创建引用:
const storage = getStorage();
const storageRef = ref(storage, `images/$img.name`); //note that ref is not a function on storage -- it's a separately imported function
设置元数据:
const metadata =
contentType: 'image/jpeg'
;
开始并监控上传:
const uploadTask = uploadBytesResumable(storageRef, file, metadata);
uploadTask.on('state_changed',
(snapshot) =>
//etc
更多文档:https://firebase.google.com/docs/storage/web/upload-files#upload_files
【讨论】:
感谢您的帮助,我是 Firebase 的新手,但仍然很困惑。现在我遇到了另一个问题。POST 400
FirebaseError: Firebase Storage: An unknown error occurred, please check the error payload for server response. (storage/unknown)
好的,我可以解决的另一个错误消息。非常感谢,你真的帮助了我。以上是关于将图像从 ReactJS 上传到 Firebase v9 存储的主要内容,如果未能解决你的问题,请参考以下文章
如何将聊天中的加载图像替换为使用 ReactJS 上传到 Firebase 存储的图像?
ref 不是函数,firebase 存储图片上传,reactJS
将图像从 imageview 上传到 Firebase Android