【发布时间】:2022-12-09 14:20:30
【问题描述】:
再会,
我正在实现一个功能,用户可以将他们的照片上传到我的 Flutter Web 应用程序,该应用程序会显示它。
我正在尝试如下所示
-
当用户上传图像文件时,它以 BYTES 的形式上传到 Firebase Storage(我知道图像文件本身不能通过 Flutter WEB 应用程序上传,必须转换为字节。是吗?)
-
字节文件的下载 URL 存储在 Firestore 中。
-
我的应用找到下载 URL 并使用该 URL 显示图像文件(字节)(如果是)。
使用的方法是
Image.network(downloadURL),但是url中的文件好像必须是图片文件,否则会报错。我想知道如何在 Flutter WEB 应用程序中显示从下载 URL 转换为 BYTES 的图像文件。
或者将图像文件本身上传到 Flutter WEB 应用程序中的 Firebase Storage。
应用程序找到带有以下代码的下载 URL
String? profileDownloadURL; @override initState() { super.initState(); email = FirebaseAuth.instance.currentUser!.email; getProfileURL(); } getProfileURL() async { DocumentSnapshot<Map<String, dynamic>> documentSnapshot = await FirebaseFirestore.instance.collection('Users').doc(email).get(); setState(() { profileDownloadURL = documentSnapshot.data()!['profileDownloadURL']; }); print('profile: $profileDownloadURL'); }用户可以使用以下方法选择图像文件
startWebFilePicker() async { FilePickerResult? result = await FilePicker.platform.pickFiles(); if (result != null) { final email = FirebaseAuth.instance.currentUser!.email; final storageRef = FirebaseStorage.instance.ref(); final profileRef = storageRef.child(email!).child(result.files.single.name); try { // upload a byte-converted image file to Firebase Storage await profileRef.putData(result.files.single.bytes!); // update download URL on Firestore String downloadURL = await profileRef.getDownloadURL(); FirebaseFirestore.instance.collection('Users').doc(email).set( {'profileDownloadURL': downloadURL}, SetOptions(merge: true), ); } on FirebaseException catch (e) { print('1: $e'); } catch (e) { print('2: $e'); } } else { // User canceled the picker } }应用程序显示图像如下
Container( child: profileDownloadURL != null ? CircleAvatar( radius: 100, backgroundImage: Image.network( profileDownloadURL!, fit: BoxFit.fill, ).image, ) : const CircleAvatar( radius: 100, child: Icon( Icons.person, ), ), ),
【问题讨论】:
标签: flutter dart google-cloud-firestore