Flutter - Upload Image to Firebase Storage

Josh Kahane picture Josh Kahane · Aug 15, 2018 · Viewed 15.6k times · Source

I get an image from Firebase Storage, take a photo with the camera, or pick one from the Library. When one of these is complete, I have a class which stores an Image so that I can use it when required.

Now I need to upload this image to Firebase Storage (modified or new, doesn't matter). Firebase allows me to use one of the following: putData or putFile, each needing either an Uint8List or File respectively.

How can I take my Image and either get a File or Uint8List from it for uploading?

--

Alternatively to remedy this, how can I get a File of my image when I retrieve it from Firebase Storage?

Either way results in providing the correct data type to upload the image, be it get a File at the start or end.

Answer

Nash picture Nash · Aug 15, 2018

When you select an image with the image picker, it returns a File, you can use await to wait until the user selects a file then store it as a File. Here is some sample code of how you can get the file from the image picker and upload it to Firebase.

    FirebaseStorage _storage = FirebaseStorage.instance;

    Future<Uri> uploadPic() async {

    //Get the file from the image picker and store it 
    File image = await ImagePicker.pickImage(source: ImageSource.gallery);  

    //Create a reference to the location you want to upload to in firebase  
    StorageReference reference = _storage.ref().child("images/");

    //Upload the file to firebase 
    StorageUploadTask uploadTask = reference.putFile(file);

    // Waits till the file is uploaded then stores the download url 
    Uri location = (await uploadTask.future).downloadUrl;

    //returns the download url 
    return location;
   }