【问题标题】:Firebase Storage REST APIFirebase 存储 REST API
【发布时间】:2020-01-25 22:37:30
【问题描述】:

我的 Flutter 应用需要非常简单的静态图像服务器。我正在考虑云存储,因为我不想担心自己的服务器管理。我正在使用实验性 Flutter for Desktop 作为移动应用程序准备数据的工具,因此我只能使用 REST API。我发现 Firebase Storage 没有自己的 REST API,而是使用 Google Cloud 的。要将图像上传到 Cloud Storage,我应该这样做:

curl -X POST --data-binary @[IMAGE_LOCATION] \
-H "Authorization: Bearer [OAUTH2_TOKEN]" \
-H "Content-Type: image/jpeg" \
"https://www.googleapis.com/upload/storage/v1/b/[BUCKET_NAME]/o?uploadType=media&name=[IMAGE_NAME]"

问题是我无法理解如何从我的 Dart 代码中获取 [OAUTH2_TOKEN](访问令牌),以及如何管理我的图像(我应该使用 Firebase Admin SDK 做些什么吗?)

有人可以帮帮我吗?

【问题讨论】:

    标签: firebase flutter dart google-cloud-firestore firebase-authentication


    【解决方案1】:

    我找到了这个问题的答案。首先,您需要在 Firebase 设置中为服务帐户创建私钥。然后使用 dart 包 googleapis_authhttp 获取访问令牌。

    var accountCredentials = ServiceAccountCredentials.fromJson({
      "private_key_id": "<please fill in>",
      "private_key": "<please fill in>",
      "client_email": "<please fill in>@developer.gserviceaccount.com",
      "client_id": "<please fill in>.apps.googleusercontent.com",
      "type": "service_account"
    });
    
    var scopes = [
      'https://www.googleapis.com/auth/cloud-platform',
    ];
    
    var client = Client();
    AccessCredentials credentials = await obtainAccessCredentialsViaServiceAccount(accountCredentials, scopes, client);
    String accessToken = credentials.accessToken.data;
    
    File image = File('path/to/image');
    
    var request = Request(
      'POST',
      Uri.parse('https://www.googleapis.com/upload/storage/v1/b/[BUCKET_NAME]/o?uploadType=media&name=images/$imageName'),
    );
    request.headers['Authorization'] = "Bearer $accessToken";
    request.headers['Content-Type'] = "image/jpeg";
    request.bodyBytes = await image.readAsBytes();
    
    Response response = await Response.fromStream(await request.send());
    print(response.statusCode);
    client.close();
    

    获取请求,您可以使用类似的方式,但您必须将 firebase 路径编码为图像:

    var imagePath = 'images/img.jpg';
    var encodedImagePath = Uri.encodeQueryComponent(imagePath);
    var request = Request(
      'GET', 
      Uri.parse('https://www.googleapis.com/storage/v1/b/[BUCKET_NAME]/o/$encodedImagePath?alt=media'),
    );
    request.headers['Authorization'] = "Bearer $accessToken";
    

    谷歌云 REST API:https://cloud.google.com/storage/docs/downloading-objects

    【讨论】:

      猜你喜欢
      • 2021-03-31
      • 2016-10-04
      • 2020-11-26
      • 2018-01-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-18
      相关资源
      最近更新 更多