0

i want to upload image to Firebase Storage, but I noticed most of the code available online (except documentation) has deprecated. as i am new to flutter, I read documentation for image picker and firestore. i was able to figure out image picker, but uploading in bucket of firestore is giving me the tough time.

below is the code for imagepicker,that i managed to do correctly:

 File _image;
     final picker = ImagePicker();
    
    Future getImage() async {
          final pickedFile =  await ImagePicker().getImage(source: ImageSource.camera);
          setState(() {
            if (pickedFile != null) {
              _image = File(pickedFile.path);
    
    
            } else {
              print('No image selected.');
            }
    
          });
        }

now i dont know how to complete the upload to Firebase Storage function:

Future UploadImage(BuildContext context) async{

String filename = basename(_image.path);
firebase_storage.FirebaseStorage storage = firebase_storage.FirebaseStorage.instance;



// how to proceed?


}
1

1 Answer 1

8

Since you have the file name. I will use your code only for that.

String filename = basename(_image.path);

Reference storageReference = FirebaseStorage.instance.ref().child("<Bucket Name>/$filename");

After having a reference to your bucket now you need to put the file in that bucket.

final UploadTask uploadTask = storageReference.putFile(file);

Now you need the url of the image. For that you need to wait till the upload completes.

final TaskSnapshot downloadUrl = (await uploadTask);

Now after this is done you can get the URL of the file using

final String url = await downloadUrl.ref.getDownloadURL();

This answer is for the version number firebase_storage: ^5.2.0

Hope this helps. Let me know if any doubts.

Sign up to request clarification or add additional context in comments.

4 Comments

yes, it worked, thanks a ton. i had uploaded image to firestore before, but that code was depreciated. and i had an issue in reading the documentation being a beginner. i thank you for explaining each step. cheers!!
No problem happy to help.
@pradyot1996 is there a way on how to rollback the upload if by mistake I choose a big file ?
@mohamed stackoverflow.com/a/54175316/8244668 found this to delete a file. Have not tried it by myself yet.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.