简体   繁体   中英

How to upload image to Firebase Storage and get the DownloadUrl Flutter

im trying to make this app to learn the methods to use in Firebase, now, im using Cloud Firestore + Storage, but im getting this error:

Exception has occurred.
FirebaseException ([firebase_storage/object-not-found] No object exists at the desired reference.)

im soo new on firebase so i dont know what to do... also there were a lot of updates and changes and some replies in other posts are deprecated...

  Future<void> uploadPic(File foto) async {
    final Reference postImageRef = FirebaseStorage.instance.ref().child('Post Images');
    var timeKey = DateTime.now();

    await postImageRef.child(timeKey.toString() + "jpg").putFile(foto)
    .whenComplete(() async { //IM GETTING THE ERROR HERE

    await postImageRef.getDownloadURL().then((value) { //IM GETTING THE ERROR HERE
        posts.imageUrl = value;
      });
    });
  return posts.imageUrl;
  }

and here is the submit of the button "save"

  void _submit() async {
    if (!formKey.currentState.validate()) return null;
    formKey.currentState.save();

    uploadPic(foto);
    subirPost(posts);
    print(posts.datetime);
    mostrarToast('Producto guardado');
  }

The error here is that you do not wait for the downloaded image link to return to you using this method:

Note: If you want to upload and write at the same time, you must wait for the completion of the lifting and then write.

1- First, create an external file that contains all the related services in Firebase, let's say its name is Api , and add this method in it:

static Future<dynamic> postFile(
      {@required File imageFile, @required String folderPath}) async {
    String fileName = DateTime.now().millisecondsSinceEpoch.toString();

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

    TaskSnapshot storageTaskSnapshot =await reference.putFile(imageFile);

    print(storageTaskSnapshot.ref.getDownloadURL());

    var dowUrl = await storageTaskSnapshot.ref.getDownloadURL();


    return  dowUrl;
  }

2- When the image is uploaded, this method will return you the link to download the image in Firebase, store it in the object as described below:

 String imgUrl = await Api.postFile(
        imageFile: image,
        folderPath: 'image');

    if (imgUrl != null) {

      posts.imageUrl = imgUrl;

      ///Type here the command that will write to the firestore
    }

Check Out This Working Code Need An uuid Package: https://pub.dev/packages?q=uuid

File _image;
final pickedFile = await ImagePicker()
    .getImage(source: ImageSource.camera, imageQuality: 80);
final String filePath = pickedFile != null ? pickedFile.path : '';
if (filePath.isNotEmpty) {
  _image = File(filePath);
  if (_image != null) {
    if (_image != null) {
      final Reference sref = storageReference
          .child('chat_multimedia/images/')
          .child(uuid.v4());

      final UploadTask storageUploadTask = sref.putFile(
        _image,
        SettableMetadata(
          contentType: mime(basename(_image.path)),
        ),
      );
      if (storageUploadTask.snapshot.state == TaskState.success) {
        final String url = await sref.getDownloadURL();
        print('The download URL is ' + url);
      } else if (storageUploadTask.snapshot.state == TaskState.running) {
        storageUploadTask.snapshotEvents.listen((event) {
          percentage = 100 *
              (event.bytesTransferred.toDouble() /
                  event.totalBytes.toDouble());
          print('THe percentage ' + percentage.toString());
        });
      } else {
        print('Enter A valid Image');
      }

      await storageUploadTask.whenComplete(() async {
        final String downloadUrl = await sref.getDownloadURL();
      });
    }
  }
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM