【发布时间】:2020-04-19 11:55:24
【问题描述】:
我能够从我的服务器生成signedUrls 并将其发送回我的React Native (expo) 客户端。
客户端还可以使用图像对象向signedUrl 发送put 请求,该图像对象包括存储在设备上的图像的uri。
问题是保存在 Google Cloud 中的图像显示已损坏。我想我必须添加其他设置才能正确上传图像。
生成 URL 的服务器代码
const { Storage } = require("@google-cloud/storage");
const storage = new Storage({keyFilename: "keys.json"});
const bucketName = "bucket";
const bucket = storage.bucket(bucketName);
const { v4 } = require("uuid");
async upload(req, res, next) {
const options = {
action: "write",
expires: Date.now() + 15 * 60 * 1000, // 15 minutes,
contentType: "image/jpeg"
};
const fileName = `1234/${v4()}.jpg`
const [url] = await bucket.file(fileName).getSignedUrl(options);
res.send(url)
}
来自服务器的预签名 URL 示例
const url = "https://storage.googleapis.com/bucket/1234/00bae114-87e4-4647-94d3-31115453e9bd.jpg?GoogleAccessId=id%40num.iam.gserviceaccount.com&Expires=1587297408&Signature=signaturecode"
图像对象示例
const image = {
"name": "IMG_4831.JPG",
"type": "image/jpeg",
"uri": "assets-library://asset/asset.JPG?id=AC24211D-E728-44D2-8B00-29EF04EC74E0&ext=JPG"
}
React Native 代码通过预签名 URL 发送图像
import axios from "axios";
const image = {uri, type: "image/jpeg", name };
await axios.put(url, image, {
headers: { "Content-Type": "image/jpeg" }
});
【问题讨论】:
-
您可以尝试将 contentType 更改为纯文本/文本等其他内容吗?这可能是与此相关的问题。
标签: react-native axios google-cloud-storage expo pre-signed-url