我读了很多这样的帖子如何将多个文件上传到 Firebase?之前关于这个问题,我尝试了不同的选择,但无法得到结果。
我正在使用 React Hook Form 来创建一个非常巨大的表单,现在我必须添加更多输入(以上传文件),并且需要帮助立即完成所有操作。
我的更新一个文件的代码:
const onChangeFile = async (e: any) => {
const file = e.target.files[0];
const storageRef = app.storage().ref();
const fileRef = storageRef.child(file.name);
await fileRef.put(file);
setFileUrl(await fileRef.getDownloadURL());
};
const onSubmit = async (data: any) => {
try {
await db
.collection('listings')
.doc()
.set({ ...data, created: new Date(), uid: currentUser.uid, file: fileUrl });
reset();
} catch (error) {
}
};
因此,正如您所看到的,仅上传一个文件非常简单,但上传多个文件时情况就不同了。问题是,我的 onSubmit 中需要更多函数,它本身就是一个异步函数,因此限制了我可以在其中执行的操作量。
有人有一个简单的解决方法吗?
If e.target.files
有多个文件,那么您可以将上传操作推送到数组,然后使用Promise.all()
:
const onChangeFile = async (e: any) => {
const storageRef = app.storage().ref();
const fileUploads = e.target.files.map(file => storageRef.child(file.name).put(file));
const fileURLReqs = (await Promise.all(fileUploads)).map(f => f.ref.getDownloadURL())
const fileUrls = await Promise.all(fileURLReqs)
// setFileUrl(await fileRef.getDownloadURL());
};
fileUrls
将是所有上传图像的 URL 数组onSubmit
如果需要,可以上传到 Firestore。
我不确定您是否要为每个图像添加新文档,但如果是,请尝试以下操作:
// in onSubmit
const listingsCol = db.collection("listings")
const files = [] // get that fileUrls array from your state
const updates = files.map(file => listingsCol.add({...data, file}))
await Promise.all(updates)
// this will add a new document for each new file uploaded
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)