Home > OS >  How I get file url from firestore path in flutter
How I get file url from firestore path in flutter

Time:09-15

When upload audio file then I gave firestorage file path , it's uploading successfully but I want to get file URL in to logged user details in firestore that's also insert correctly in firestore but not file URL that is file path. How I get URL from file path.

//firestorage upload 
     Future<void> _onFileUploadButtonPressed() async {
        FirebaseStorage firebaseStorage = FirebaseStorage.instance;
    
        setState(() {
          _isUploading = true;
        });
        try {
          await firebaseStorage
              .ref()
              .child("${loggedInUser.uid}/records1")
              .child(
                  _filePath.substring(_filePath.lastIndexOf('/'), _filePath.length))
              .putFile(File(_filePath));
    
          widget.onUploadComplete();
          onsend();
        } catch (error) {
          print('Error occured while uplaoding to Firebase ${error.toString()}');
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(
              content: Text('Error occured while uplaoding'),
            ),
          );
        } finally {
          setState(() {
            _isUploading = false;
          });
        }
      }

    //firestore URL upload 
     Future<void> onsend() async {
        //uploading to cloudfirestore
        FirebaseFirestore firebaseFirestore = FirebaseFirestore.instance;
    
        await firebaseFirestore
            .collection("users")
            .doc("${loggedInUser.uid}")
            .collection("reco")
            .add({'downloadURL': _filePath}).whenComplete(() =>
                showSnackBar("Image uploaded successful", Duration(seconds: 2)));
      }

CodePudding user response:

This is my code I use upload and get image url from Firebase storage:

Future<String> uploadImageToFirebase(File imageFile) async {
    var user = StaticVariable.myUser!;
    String imagePath = '';
    try {
      String downloadUrl;
      FirebaseStorage firebaseStorage = FirebaseStorage.instance;
      Reference ref = firebaseStorage.ref(
          'uploads-images/${user.profileId}/images/${DateTime.now().microsecondsSinceEpoch}');
      TaskSnapshot uploadedFile = await ref.putFile(imageFile);
      if (uploadedFile.state == TaskState.success) {
        downloadUrl = await ref.getDownloadURL();
        imagePath = downloadUrl;
      }
      return imagePath;
    } catch (e) {
      return '';
    }
  }

I try to improve from above code:

Future<void> _onFileUploadButtonPressed() async {
  FirebaseStorage firebaseStorage = FirebaseStorage.instance;
  String downloadUrl = '';
  setState(() {
    _isUploading = true;
  });
  try {
    Reference ref = firebaseStorage
        .ref()
        .child("${loggedInUser.uid}/records1")
        .child(
        _filePath.substring(_filePath.lastIndexOf('/'), _filePath.length));
    TaskSnapshot uploadedFile = await ref.putFile(File(_filePath));

    if (uploadedFile.state == TaskState.success) {
      downloadUrl = await ref.getDownloadURL();
    }
    widget.onUploadComplete();
    onsend();//send downloadURL after get it
  } catch (error) {
    print('Error occured while uplaoding to Firebase ${error.toString()}');
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text('Error occured while uplaoding'),
      ),
    );
  } finally {
    setState(() {
      _isUploading = false;
    });
  }
}
  • Related