Get Download URL from Firebase Storage in Flutter
Asked Answered
M

18

25

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.

Myosotis answered 25/1, 2018 at 3:50 Comment(7)
How do you upload the image? I haven't seen a simple way to get a download path from a StorageReference yet. I think the Firebase Storage plugin is still missing some features to be able to do something like shown in firebase.google.com/docs/storage/web/download-filesUracil
As Gunter mentioned, there's no way get the download path before uploading the image in first place.Opah
Why do you need it before?Jovia
I uploaded the image manually from firebase console. It just a few lines to wrap native firebase storage library to flutter platform channel. Well I've done it by extending current plugin to my ownMyosotis
This isn't implemented yet, but we're working on it. In the meantime pull requests are very welcome.Lickspittle
@CollinJackson Is there an issue I can subscribe to? How to I follow progress on this?Propel
I sent a pull request for this github.com/flutter/plugins/pull/390/filesPropel
B
32

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; 
}
Bioscope answered 18/10, 2018 at 16:24 Comment(3)
Now that's the correct way to do it. Thanks, mate, spent like two hours figuring out wtf!Schulein
The above way is now deprecated, check this answer: https://mcmap.net/q/505965/-undefined-class-storagereference-when-using-firebase-storageCaudal
Can you please check out my question if possible #68351597Rebbecarebbecca
C
11

use url like this:

printUrl() async {
    StorageReference ref = 
        FirebaseStorage.instance.ref().child("images/sky.jpg");
    String url = (await ref.getDownloadURL()).toString();
    print(url);
}
Cistern answered 26/9, 2018 at 8:19 Comment(0)
K
8

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);

    });
Knockout answered 7/11, 2020 at 21:22 Comment(3)
Thanks a lot for this answer!Buxom
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<List<String>> _uploadFiles(List<PickedFile> files) async {``` in previous version it is working fine with StorageTaskSnapshot snapshot = await uploadTask.onComplete; because of "await" inside for loop.Polito
This is the perfect solutionLilianaliliane
D
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;
}
Dogeared answered 26/2, 2018 at 5:25 Comment(4)
if I want to downlaod all files from a folder, can I just provide the folder name?Whereon
#37335602Dogeared
put is deprecated. Make use of putFile .Engross
The getter 'future' isn't defined for the class 'StorageUploadTaskAdiell
R
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");
  });
}
});
}
Radnorshire answered 18/7, 2021 at 13:35 Comment(1)
Thank you for this answer with the latest version, I was looking for something like this !Labiovelar
J
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;}
Jordanson answered 12/9, 2019 at 20:56 Comment(1)
You should consider adding text to explain the code in the answerCorrinacorrine
E
1

He is my solution :

StorageReference storageReference = FirebaseStorage.instance.ref().child("myfile"); 
StorageUploadTask uploadTask = storageReference.putFile(file);
uploadTask.onComplete.then((s){ 
   s.ref.getDownloadURL(); 
});
Eldredge answered 8/7, 2019 at 8:46 Comment(0)
S
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);
    }
  }
Speight answered 4/9, 2019 at 9:49 Comment(0)
E
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;
  }
Excretory answered 8/2, 2021 at 11:2 Comment(0)
F
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();
}
Flagler answered 25/2, 2022 at 6:15 Comment(0)
M
1

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}');
 }

}

Marble answered 2/8, 2023 at 23:47 Comment(0)
B
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

Baumbaugh answered 18/4, 2020 at 17:20 Comment(0)
Q
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());
Qualitative answered 5/10, 2020 at 18:48 Comment(0)
D
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;
  });
}

}

Diverge answered 11/7, 2021 at 16:55 Comment(0)
V
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/...

Vining answered 8/10, 2021 at 13:19 Comment(0)
C
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();
  }
}
Coumarin answered 7/2, 2022 at 3:26 Comment(0)
T
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;

}

Traweek answered 24/2, 2022 at 15:2 Comment(2)
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?Margemargeaux
There is nothing in this answer that has not been posted years ago by the others.Oina
K
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;
  }
Kynthia answered 31/3, 2022 at 15:31 Comment(1)
Can't work. Does uploadTask have ref props?Baynebridge

© 2022 - 2025 — McMap. All rights reserved.