首页 > 解决方案 > Firebase 存储 REST API

问题描述

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

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]"

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

有人可以帮我吗?

标签: firebaseflutterdartgoogle-cloud-firestorefirebase-authentication

解决方案


我找到了这个问题的答案。首先,您需要在 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


推荐阅读