【问题标题】:FireBase & Firebase Storage - is it possible to upload file to Storage and record the url into FireBase [closed]FireBase 和 Firebase 存储 - 是否可以将文件上传到存储并将 URL 记录到 FireBase [关闭]
【发布时间】:2021-09-29 04:02:02
【问题描述】:
我想知道当我将例如3个文件上传到存储中时,我是否可以同时在FireStore数据库中记录存储中记录的名称。目标是能够在页面中显示保存在存储中的图片,但仅限于特定文档中。
我不确定它是否足够清楚。如果不是这样,我可以给更多的颜色。
谢谢。
【问题讨论】:
-
是的,这完全有可能。您应该首先上传文件,然后,对于每个文件,使用 getDownloadURL 方法获取长期下载 URL,并将 URL 保存在 Firestore 文档中。您应该尝试通过编写一些代码来实现这种建议的方法,如果您的代码遇到一些问题,请提出一个具体问题。换句话说,您的问题需要更多关注,请参阅How to ask
-
标签:
firebase
flutter
firebase-storage
【解决方案1】:
您确实可以通过putFile 方法上传图片,并通过getDownloadUrl 方法检索上传的文档网址。
这是一个上传文件功能的示例代码:
Future<void> uploadFile(File file) async {
try {
Reference ref = FirebaseStorage.instance
.ref('avatars/avatar1.png');
TaskSnapshot task = await ref.putFile(file);
// Here you can keep your URL to later save it in a firestore document for example
documentUrl = await task.ref.getDownloadURL();
} on FirebaseException catch (e) {
// Todo handle exceptions
}
}
通常我喜欢添加一个布尔值 isLoading,将我的上传函数包装在真假 setState 之间。这样我就可以轻松管理覆盖或加载屏幕,以在必要时禁用任何用户输入。