Flutter上传图片到Firebase Storage如何获取downloadUrl并存入Firestore
问题根因
你当前的代码在文件上传到Firebase Storage完成后,直接将本地文件名存入了Firestore,自然不是可访问的公网链接,你需要在文件上传成功后,调用对应Storage引用的getDownloadURL()方法获取可用的https链接,再将该链接写入Firestore。
正确调用位置
getDownloadURL()需要在putFile上传执行完成之后调用,你可以先把Storage引用提取为变量方便后续复用。
修改后的完整代码
Future<void> _uploadProfilePhoto(String inputSource) async { final picker = ImagePicker(); PickedFile? pickedImage; try { pickedImage = await picker.getImage( source: inputSource == 'camera' ? ImageSource.camera : ImageSource.gallery, maxWidth: 1920); final String fileName = path.basename(pickedImage!.path); File imageFile = File(pickedImage.path); try { // 先提取存储引用变量,方便上传后调用getDownloadURL final avatarRef = storage.ref("avatars/$fileName"); await avatarRef.putFile( imageFile, SettableMetadata(customMetadata: { 'uploaded_by': '$uid', })); // 上传完成后获取下载链接,必须加await等待结果返回 final String downloadUrl = await avatarRef.getDownloadURL(); // 将拿到的下载链接存入Firestore users.doc(uid).update({ "profilePhoto": downloadUrl, }); setState(() {}); } on FirebaseException catch (error) { print(error); } } catch (err) { print(err); } }
注意事项
- 必须给
getDownloadURL()加上await,否则你存入Firestore的会是Future实例而不是实际的链接字符串 - 需要确认你的Firebase Storage安全规则允许对应文件的读权限,否则即使拿到链接也可能无法正常访问
内容的提问来源于stack exchange,提问作者DB Cooper
相关产品推荐
相关产品推荐

