简体   繁体   中英

Flutter Firestore Storage get downloadUrl

I need to get the downloadURL from uplaoding a photo to a Firebase Storage so I can store it inside of a Firestore document. The issue with my code is that the URL that is saved isnt a https//: so I need to get the downloadURL. I was wondering where I need to call it to get the downloadUrl and save it inside of my Firestore Database.

Here is my code:

  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 {
        await storage.ref("avatars/$fileName").putFile(
            imageFile,
            SettableMetadata(customMetadata: {
              'uploaded_by': '$uid',
            }));
            
        // Create/Update firesotre document
        users.doc(uid).update({
          "profilePhoto": fileName,
        });

        setState(() {});
      } on FirebaseException catch (error) {
        print(error);
      }
    } catch (err) {
      print(err);
    }
  }

You can call getDownloadURL() on the reference at any time after the file upload has completed. So this would be a good spot:

await storage.ref("avatars/$fileName").putFile(
    imageFile,
    SettableMetadata(customMetadata: {
      'uploaded_by': '$uid',
    }));
var downloadURL = await storage.ref("avatars/$fileName")..getDownloadURL();       
// Create/Update firesotre document
users.doc(uid).update({
  "profilePhoto": downloadURL,
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM