简体   繁体   English

如何将图片上传到 Firebase 存储并获取 DownloadUrl Flutter

[英]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:我试图让这个应用程序学习在 Firebase 中使用的方法,现在,我正在使用 Cloud Firestore + Storage,但我收到了这个错误:

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...我是 firebase 的新人,所以我不知道该怎么办……还有很多更新和更改,其他帖子中的一些回复已被弃用……

  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: 1- 首先,在 Firebase 中创建一个包含所有相关服务的外部文件,假设它的名称为Api ,并在其中添加此方法:

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: 2- 上传图片后,此方法会返回Firebase中的图片下载链接,如下所述将其存储在object中:

 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查看此工作代码需要 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();
      });
    }
  }
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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