Good day,
I'm implementing a function that users can upload their picture on my Flutter Web app and the app shows it.
I'm trying to make this as below
When a user uploads an image file, it is uploaded on Firebase Storage as BYTES (I know that an image file itself can't upload by Flutter WEB app, must be converted to bytes. true?)
The download URL of the bytes file is stored in Firestore.
My app finds the download URL and shows the image file(bytes) using the URL if it is.
The method used is Image.network(downloadURL)
, but it seems the file in the url must be an image file, otherwise, throws an error.
I wonder how to show an image file converted to BYTES from the download URL in the Flutter WEB app.
Or upload an image file itself to Firebase Storage in the Flutter WEB app.
App finds download URL with below code
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');
}
User can select an image file with below method
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
}
}
App shows an image as below
Container(
child: profileDownloadURL != null
? CircleAvatar(
radius: 100,
backgroundImage: Image.network(
profileDownloadURL!,
fit: BoxFit.fill,
).image,
)
: const CircleAvatar(
radius: 100,
child: Icon(
Icons.person,
),
),
),