Search code examples
file-uploadgoogle-cloud-functionsfirebase-storageimage-uploadflutter-web

Flutter web - Upload Image File to Firebase Storage


On flutter web, I pick an image file from the computer and get a File image object. Then I want to upload it to Firebase Storage. For Android and iOS versions of the app I was using a Firebase Cloud Function and an http multipart request. It worked, but for the web version of the app it doesn't. So,

How can I upload an html image file to Firebase Storage, either directly or through a Cloud Function?


Solution

  • Finally I managed to find a solution to this issue. To achieve this I needed to install two dependencies, firebase and universal_html. Yet difficult to find out the solution, its implementation was actually simple. Here is the code of the function I used to upload the html image file to Firebase Storage, into the "images" folder:

    import 'dart:async';
    import 'package:universal_html/prefer_universal/html.dart' as html;
    import 'package:firebase/firebase.dart' as fb;
    
    Future<Uri> uploadImageFile(html.File image,
          {String imageName}) async {
        fb.StorageReference storageRef = fb.storage().ref('images/$imageName');
        fb.UploadTaskSnapshot uploadTaskSnapshot = await storageRef.put(image).future;
        
        Uri imageUri = await uploadTaskSnapshot.ref.getDownloadURL();
        return imageUri;
    }
    
    

    I hope it helps someone with the same need as me.