23

I'm currently exploring Flutter, I found there is an official Firebase Storage plugin in Flutter firebase_storage I have storage reference like this one:

final StorageReference ref = FirebaseStorage.instance.ref().child("default.png");

But there is no method to get download URL from that StorageReference.

Putra Ardiansyah
  • 5,249
  • 4
  • 25
  • 37

18 Answers18

29

If the above solution doesn't work, try this:

Future<String> uploadImage(var imageFile ) async {
    StorageReference ref = storage.ref().child("/photo.jpg");
    StorageUploadTask uploadTask = ref.putFile(imageFile);

    var dowurl = await (await uploadTask.onComplete).ref.getDownloadURL();
    url = dowurl.toString();

    return url; 
}
Evan Wieland
  • 1,445
  • 1
  • 20
  • 36
Alex Moon
  • 319
  • 3
  • 4
  • Now that's the correct way to do it. Thanks, mate, spent like two hours figuring out wtf! – jujka Aug 04 '19 at 09:24
  • 3
    The above way is now deprecated, check this answer: https://stackoverflow.com/a/64764390/7015400 – Peter Haddad Nov 10 '20 at 08:27
  • Can you please check out my question if possible https://stackoverflow.com/questions/68351097/reading-firebase-storage-image-security-rules – Noobdeveloper Jul 12 '21 at 18:04
11

use url like this:

printUrl() async {
    StorageReference ref = 
        FirebaseStorage.instance.ref().child("images/sky.jpg");
    String url = (await ref.getDownloadURL()).toString();
    print(url);
}
Dan Alboteanu
  • 9,404
  • 1
  • 52
  • 40
7

At latest version firebase_storage: ^5.0.1 Approach should be like below:

Reference reference = FirebaseStorage.instance.ref().child("SupportChatImages").child(fileName);

    UploadTask uploadTask =  reference.putFile(imageFile);

    uploadTask.whenComplete(() async{

      try{
        imageUrl = await reference.getDownloadURL();
      }catch(onError){
        print("Error");
      }

      print(imageUrl);

    });
Md Mahmudul Islam
  • 2,514
  • 4
  • 18
  • 33
  • 1
    Thanks a lot for this answer! – Krishna Shetty Dec 02 '20 at 16:21
  • Hello, This works for 1 file, However I am not sure hot to make it working for a list of files. I need to do something like ``` Future> _uploadFiles(List files) async {``` in previous version it is working fine with StorageTaskSnapshot snapshot = await uploadTask.onComplete; because of "await" inside for loop. – Ishaan Puniani Dec 06 '20 at 00:47
  • This is the perfect solution – Dario Brux Sep 12 '22 at 20:11
6

I had Implemented a method to save your image with a timestamp and get the downloadable url.

Future<String>photoOption() async {
    try {
        DateTime now = new DateTime.now();
        var datestamp = new DateFormat("yyyyMMdd'T'HHmmss");
        String currentdate = datestamp.format(now);
        File imageFile = await ImagePicker.pickImage();


        StorageReference ref = FirebaseStorage.instance
            .ref()
            .child("images")
            .child("$currentdate.jpg");
        StorageUploadTask uploadTask = ref.putFile(imageFile);

        Uri downloadUrl = (await uploadTask.future).downloadUrl;
        addUser.downloadablelink = downloadUrl.toString();

        downloadableUrl = downloadUrl.toString();

        print(downloadableUrl);

    } catch (error) {
        print(error);
    }

    return downloadableUrl;
}
Alex Meuer
  • 1,621
  • 3
  • 26
  • 37
siva kumar
  • 2,745
  • 6
  • 19
  • 29
5

For firebase_storage: ^10.0.1

Here is the code to get URL of Uploaded Image..

uploadImagetFirebase(String imagePath) async {
 await FirebaseStorage.instance
  .ref(imagePath)
  .putFile(File(imagePath))
  .then((taskSnapshot) {
print("task done");

// download url when it is uploaded
if (taskSnapshot.state == TaskState.success) {
  FirebaseStorage.instance
      .ref(imagePath)
      .getDownloadURL()
      .then((url) {
    print("Here is the URL of Image $url");
    return url;
  }).catchError((onError) {
    print("Got Error $onError");
  });
}
});
}
3
Future<String> urlDownload(file) async {
var uuid = Uuid().v1();
StorageReference ref =
    FirebaseStorage.instance.ref().child("post_$uuid.jpg");
StorageUploadTask uploadTask = ref.putFile(file);

String downloadUrl =
    await (await uploadTask.onComplete).ref.getDownloadURL();
return downloadUrl;}
  • 4
    You should consider adding text to explain the code in the answer –  Sep 12 '19 at 21:18
1

He is my solution :

StorageReference storageReference = FirebaseStorage.instance.ref().child("myfile"); 
StorageUploadTask uploadTask = storageReference.putFile(file);
uploadTask.onComplete.then((s){ 
   s.ref.getDownloadURL(); 
});
touti
  • 1,164
  • 6
  • 18
1

My Solution

Future mainprofile(File image) async {
    try {
      DateTime now = new DateTime.now();
      var datestamp = new DateFormat("yyyyMMdd'T'HHmmss");
      String currentdate = datestamp.format(now);
      _firebaseStorageRef = FirebaseStorage.instance
          .ref()
          .child(userRepository.uid)
          .child('main')
          .child("$currentdate.jpg");
      StorageUploadTask uploadTask = _firebaseStorageRef.putFile(image);
      uploadTask.onComplete.then((onValue) async {
        _mainurl = (await _firebaseStorageRef.getDownloadURL()).toString();
      });
    } catch (error) {
      print(error);
    }
  }
1

I have tried many ways and this worked for me after many tries as Firebase Storage removing old methods. If anyone getting error of 404 Object not found Then the below code also solves that.

Future<String> uploadSingleImage(File file) async {
    //Set File Name
    String fileName = DateTime.now().millisecondsSinceEpoch.toString() +
        AuthRepository.getUser().uid +
        '.jpg';
    
    //Create Reference
    Reference reference = FirebaseStorage.instance
        .ref()
        .child('Single Post Images')
        .child(fileName);

    //Now We have to check the status of UploadTask
    UploadTask uploadTask = reference.putFile(file);
    
    String url;
    await uploadTask.whenComplete(() async {
      url = await uploadTask.snapshot.ref.getDownloadURL();
    });
   
    return url;
  }
Arun gwalani
  • 329
  • 3
  • 4
1

try this

 Future<String> downloadFromFirebase() async {
  // Create reference
    StorageReference ref = FirebaseStorage.instance.ref().child("default.png");
    String _myUrl = await ref.getDownloadURL();
    return _myUrl.toString();
}
Sonu Saini
  • 1,814
  • 9
  • 16
0

Here is my solution

this part is how i get image from picker

 Future getImage() async {
  var image = await ImagePicker.pickImage(source: ImageSource.gallery);

  setState(() {
    _image = image;
      print('Image Path $_image');
  });
}

than i upload it

 Future uploadPic(BuildContext context) async {

  String fileName = basename(_image.path);
  StorageReference firebaseStorageRef = FirebaseStorage.instance.ref().child(fileName);
  StorageUploadTask uploadTask = firebaseStorageRef.putFile(_image);
  StorageTaskSnapshot taskSnapshot = await uploadTask.onComplete;


  final String url = (await taskSnapshot.ref.getDownloadURL());
  print('URL Is $url');
}

hope it will help someone

eko
  • 532
  • 1
  • 5
  • 12
0

Here is my approach, to upload an image to Firebase Storage and get the dowlad URL

 var img_name=DateTime.now().millisecondsSinceEpoch.toString()+".png";

 final StorageReference storageReference = FirebaseStorage.instance.ref().child("images/profile/"+img_name);

 var upload= await storageReference.putFile(croppedFile);
 await upload.onComplete;

 var url=await storageReference.getDownloadURL();
 print(url.toString());
0

**Solution for latest firebase_storage 9.0.0 **

Future<void> _uploadImage() async {
if (_image != null) {
  final fileName = '${DateTime.now()}.jpeg';
  Reference reference = _firebaseStorage.ref('uploads/$fileName');
  TaskSnapshot taskSnapshot = await reference
      .putFile(_image!)
      .whenComplete(() => reference.getDownloadURL());

  print(taskSnapshot.ref.fullPath.toString());

  setState(() {
    _imageUploadState = ImageUploadState.done;
  });
}

}

J Jiju Thomas
  • 489
  • 4
  • 3
0

For firebase_storage: ^10.0.1

import 'package:firebase_storage/firebase_storage.dart' as firebase_storage;

String image = 'gs://ID.appspot.com/image/1026_800x800.jpg';

firebase_storage.FirebaseStorage.instance.refFromURL(image).getDownloadURL().then((url) async {
                  print(url);
                });

Will download something like this: https://firebasestorage.googleapis.com/v0/b/ID.appspot.com/o/...

silexcorp
  • 1,151
  • 1
  • 12
  • 13
0

Try This

Future<String> uploadFile(XFile _file) async {
File file = File(_file.path);
try {
  var ref = FirebaseStorage.instance.ref('uploads/' + _file.name);
  var uploadTask = await ref.putFile(file);
  if (uploadTask.state == TaskState.success) {
    final url = await ref.getDownloadURL();
    return url;
  }
  return "0";
} catch (e) {
  print(e);
  return e.toString();
  }
}
Farman Ameer
  • 1,234
  • 2
  • 16
  • 22
0
Future<String> uploadImage(imageFile) async {
Reference ref = FirebaseStorage.instance.ref().child('default.png');
UploadTask uploadTask = ref.putFile(imageFile);
final snapshot = await uploadTask.whenComplete(() => {});
final urlDownload = await snapshot.ref.getDownloadURL();
print("The url is here! $urlDownload");
return urlDownload;

}

  • Remember that Stack Overflow isn't just intended to solve the immediate problem, but also to help future readers find solutions to similar problems, which requires understanding the underlying code. This is especially important for members of our community who are beginners, and not familiar with the syntax. Given that, **can you [edit] your answer to include an explanation of what you're doing** and why you believe it is the best approach? – Jeremy Caney Feb 25 '22 at 00:03
  • There is nothing in this answer that has not been posted years ago by the others. – nvoigt Mar 01 '22 at 16:43
0

My solution using Async/await syntax and newest Firebase Storage 2022

Future<String> uploadFileToStorage(String path, File image) async {
    TaskSnapshot uploadTask = await _storageReference.child(path).putFile(image);

    String pathdownlaod = await uploadTask.ref.getDownloadURL();

    return pathdownlaod;
  }
0

FIREBASE STORAGE: ^11.2.5

  uploadPhotoToFirebase(File photo) async {
   try {
    String ref = 'images/img-${DateTime.now().toString()}.jpeg';
    final storageRef = FirebaseStorage.instance.ref();
    UploadTask uploadTask = storageRef.child(ref).putFile(
     photo
    );
    var url = await uploadTask.then((task) => task.ref.getDownloadURL());
  } on FirebaseException catch (e) {
    throw Exception('Erro no upload: ${e.code}');
 }

}