【问题标题】:How to upload image to Firebase Storage and get the DownloadUrl Flutter如何将图像上传到 Firebase 存储并获取 DownloadUrl Flutter
【发布时间】:2021-03-23 09:10:42
【问题描述】:

我试图让这个应用程序学习在 Firebase 中使用的方法,现在,我正在使用 Cloud Firestore + Storage,但我收到了这个错误:

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

我是 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;
  }

这里是“保存”按钮的提交

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

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

【问题讨论】:

    标签: android firebase flutter firebase-storage


    【解决方案1】:

    这里的错误是你使用这种方法没有等待下载的图片链接返回给你:

    注意:如果要同时上传和写入,必须等待提升完成后再写入。

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

     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
        }
    

    【讨论】:

    • 嘿,我回答了写我的新代码的线程,检查一下,我在那里回复你
    【解决方案2】:

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

    【讨论】:

    • 我回答了线程来编写我的新代码,检查一下我在那里回复了你
    猜你喜欢
    • 1970-01-01
    • 2018-10-24
    • 2019-01-22
    • 2021-08-30
    • 2021-08-11
    • 1970-01-01
    • 2021-10-12
    • 2021-07-03
    相关资源
    最近更新 更多