firebase - 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 做些什么吗?)
有人可以帮我吗?
解决方案
我找到了这个问题的答案。首先,您需要在 Firebase 设置中为服务帐户创建私钥。然后使用 dart 包googleapis_auth
和http
.
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
推荐阅读
- python - 使用 Tkiner Python 对 SQLite 数据库进行动态查询
- openssl - Bash期望解密密码
- php - 如何使用分页正确发送变量?
- c# - 使用多个 TestCaseSource 属性执行 Nunit 测试用例
- mysql - 在 MySQL 中拆分值以插入不同的行
- html - 在Angular中替换innerHTML不必要地关闭标签
- matlab - 计算月中的天数 (MATLAB)
- python - Python selenium:元素不可交互
- c++ - 如何将一个数字分成几个不相等但不断增加的数字 [用于发送 PlaceOrder(OP_BUY,lots) 合约 XTO]
- git - 如何在 Gerrit 推送主题中转义空格?