无法从 firebase 存储下载 url

Cant get the download url from firebase storage

我可以成功上传图片但是无法获取上传图片的URL 另外,随着最近方法的变化,我想写一个比这更干净的代码。

try {
          await FirebaseStorage.instance
              .ref()
              .child('user_image')
              .child(authResult.user
                      .uid + //ref gives access to root cloud store , firebase manages all the tokens etc
                  '.jpg')
              .putFile(image);
        } on FirebaseException catch (e) {
          print(e);
        }
        //Download the Url
        String url = await FirebaseStorage.instance
            .ref()
            .child('user_image')
            .child(authResult.user
                    .uid + //ref gives access to root cloud store , firebase manages all the tokens etc
                '.jpg')
            .getDownloadURL();
        print('Url' + url);


我使用以下代码进行上传和下载。您错过了使用 uploadtask 属性.

   final photoRef = FirebaseStorage.instance.ref().child("photos"); 
   UploadTask uploadTask = photoRef.child("$id.jpg").putFile(photo);
   String url = await (await uploadTask).ref.getDownloadURL();

您无需使用 UploadTask 即可下载 URL。您的代码的更简单版本是:

Reference ref = FirebaseStorage.instance .ref()
  .child('user_image')
  .child(authResult.user.uid+'.jpg')
try {
  await ref.putFile(image);
  String url = await ref.getDownloadURL();
  print('Url' + url);
} on FirebaseException catch (e) {
  print(e);
}

我上面所做的:

  1. StorageReference 创建一个变量,这样您只需计算一次,然后从该变量上传和下载 URL。
  2. 移动异常处理以涵盖 getDownloadURL() 调用,因为您可能不想在上传失败时尝试获取下载 URL。

通过这两项更改,它非常地道并且非常接近 uploading files and getting download URLs 上的 FlutterFire 文档示例。