【问题标题】:How to get urls of Firebase storage and save them in Arraylist Android如何获取 Firebase 存储的 url 并将它们保存在 Arraylist Android 中
【发布时间】:2019-04-30 19:59:42
【问题描述】:

我在 this 之类的 firebase 存储中有图像,并且图像是从 firebase 控制台上传的,因此我之前无法存储 URL。我想知道是否有任何方法可以获取 URL 并将它们保存在 ArrayList 中。所以我可以稍后从那个 ArrayList 中使用。 我搜索了很多,但找不到任何可能的答案。

请:不推荐回收站视图。我只需要 Firebase 存储中所有图像的 URL。

【问题讨论】:

    标签: android firebase arraylist firebase-storage geturl


    【解决方案1】:

    正如您所提到的,由于图像是从 Firebase 控制台上传的,因此应用无法知道何时加载新图像并计算相应的 URL。

    所以这必须在后端完成,即在 Firebase 平台本身上。 Firebase 的 Cloud Functions 专门为此而设计,请参阅:https://firebase.google.com/docs/functions/

    Cloud Functions for Firebase 可让您自动运行后端代码 响应由 Firebase 功能触发的事件。

    在您的情况下,您将编写一个云函数,该函数将在文件加载到云存储时触发。此函数将计算 URL(通过 getSignedUrl() 方法)并将其保存到 Firebase 数据库,例如火库。这样,您的 Android 应用程序可以查询数据库以获取 URL 列表(并将它们放在 ArrayList 中)。

    云功能将遵循以下原则:

    const functions = require('firebase-functions');
    const admin = require('firebase-admin');
    
    //See Note below and https://stackoverflow.com/a/50138883/3371862
    import * as serviceAccount from 'yourServiceAccount.json';
    const adminConfig = JSON.parse(process.env.FIREBASE_CONFIG)
    adminConfig.credential = admin.credential.cert(<any>serviceAccount)
    admin.initializeApp(adminConfig);
    
    const defaultStorage = admin.storage();
    
    exports.saveSignedURL = functions.storage.object().onFinalize(object => {
      const file = defaultStorage.bucket(object.bucket).file(object.name);
    
      const options = {
        action: 'read',
        expires: '03-17-2025'
      };
    
      return file.getSignedUrl(options).then(results => {
        const url = results[0];
    
        return admin
          .firestore()
          .collection('images')
          .add({ url: url });
      });
    });
    

    请注意,为了使用 getSignedUrl() 方法,您需要使用专用服务帐户的凭据初始化 Admin SDK,请参阅此 SO Q&A:https://stackoverflow.com/a/50138883/3371862


    最后,如果您是 Cloud Functions 新手,您可以查看此文档page,尤其是底部的“后续步骤”部分。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-05-09
      • 1970-01-01
      • 1970-01-01
      • 2021-05-12
      • 2021-03-14
      • 2019-01-29
      • 1970-01-01
      • 2017-04-13
      相关资源
      最近更新 更多