【问题标题】:Cant get the download url from firebase storage无法从 Firebase 存储中获取下载网址
【发布时间】:2021-09-09 00:47:25
【问题描述】:

我可以成功上传图片但无法获取上传图片的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);


【问题讨论】:

    标签: flutter dart firebase-storage


    【解决方案1】:

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

    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 filesgetting download URLs 上的 FlutterFire 文档示例。

    【讨论】:

    • 正是我想要的!谢谢粉扑
    • 我对此所做的唯一更改是将StorageReference 更改为Reference。它已经改变了。
    • 不错@pannam。我更新了答案中的代码。
    【解决方案2】:

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

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

    【讨论】:

    • 谢谢,我赞成您的回答,但我想在没有 UploadTask 的情况下使用它。如果我没有得到更多答案,我会接受你的答案。
    猜你喜欢
    • 1970-01-01
    • 2018-11-20
    • 1970-01-01
    • 1970-01-01
    • 2017-05-17
    • 2020-10-20
    • 1970-01-01
    • 2021-08-09
    • 2022-01-15
    相关资源
    最近更新 更多