firebase - 如何将图像上传到 Firebase 存储并将图像 url 保存到 Firebase 数据库以在颤振中使用它
问题描述
我需要从 firebase 存储中获取图像链接并将其 url 保存到 firestore 字段,我有一个名为 avatar(string) 的字段,头像值是来自 firebase 存储的图像链接
ClipRRect(
child: Image.network(snapshot.data[index].data['avatar'],
height: 100,
width: 170,
fit: BoxFit.fill,
),
borderRadius: BorderRadius.circular(20),
),
和错误代码
════════ Exception caught by image resource service ════════════════════════════════════════════════
The following ArgumentError was thrown resolving an image codec:
Invalid argument(s): Unsupported scheme 'gs' in URI gs://pfe-2020-51d9c.appspot.com/Ail/14118b537d_100727_bienfaits-ail.jpg
When the exception was thrown, this was the stack:
#0 _HttpClient._openUrl (dart:_http/http_impl.dart:2278:9)
#1 _HttpClient.getUrl (dart:_http/http_impl.dart:2197:48)
#2 NetworkImage._loadAsync (package:flutter/src/painting/_network_image_io.dart:84:59)
#3 NetworkImage.load (package:flutter/src/painting/_network_image_io.dart:47:14)
#4 ImageProvider.resolve.<anonymous closure>.<anonymous closure>.<anonymous closure> (package:flutter/src/painting/image_provider.dart:327:17)
...
Image provider: NetworkImage("gs://pfe-2020-51d9c.appspot.com/Ail/14118b537d_100727_bienfaits-ail.jpg", scale: 1.0)
Image key: NetworkImage("gs://pfe-2020-51d9c.appspot.com/Ail/14118b537d_100727_bienfaits-ail.jpg", scale: 1.0)
══════════════════════════════════════════════════ ═══════════════════════════════</p>
解决方案
1)创建文件变量来保存你的形象:
您可以使用image_picker从手机中选择图像。
File file;
2)创建功能以选择图像
handleChooseImageFromGallery() async {
File _file = await ImagePicker.pickImage(source: ImageSource.gallery);
setState(() {
this.file = _file;
});
}
如果要使用手机摄像头拍摄图像,可以在源代码中传递ImageSource.camera 。
3)将图像上传到 Firebase 存储
Future<String> handleUploadImage(imageFile) async {
// Upload imageFile to firebase storage
// TODO: use uuid for pictureId
StorageUploadTask uploadTask =
storageRef.child("${user.id}_profilePic_$picId.jpg").putFile(imageFile);
StorageTaskSnapshot storageTaskSnapshot = await uploadTask.onComplete;
// Once the image is uploaded to firebase get the download link.
String downlaodUrl = await storageTaskSnapshot.ref.getDownloadURL();
return downlaodUrl;
}
此函数将返回图像 url。
4)将图像 url 保存在 firestore 文档中
void handleUpdateUserProfile()
{
String mediaUrl = await handleUploadImage(file); // Pass your file variable
// Create/Update firesotre document
usersRef.document(userId).updateData(
{
"avatar": mediaUrl,
}
);
}
推荐阅读
- header - 滚动时如何使内容不在固定导航栏下方?
- jupyter-notebook - 使图像网格框可滚动
- c - 如何存储守护进程?
- python - 在使用 Jupyter notebook 在 Sentiment Analysis 中定义 get Analysis (score) 时遇到缩进错误
- node.js - 在单个命令中运行多个 NodeJS 服务器
- ios - Firebase AppCheck 的用途是什么?
- firebase - Flutter:如何定义 Firestore 集合的模型或 Firestore 字段的数据类型?
- reactjs - .gitignore 中的 Gitlab node_modules,如何仍然编辑和推送模块
- python-3.x - 如何使用 Postman 在 DRF 中上传个人资料图片(如果可能,不创建单独的端点)
- json - 将 JSON 数据解析为列表 (Dart)