gpt4 book ai didi

android - 将 Base64 字符串上传到 Google Cloud Storage

转载 作者:行者123 更新时间:2023-11-30 01:35:03 24 4
gpt4 key购买 nike

在我的 App Engine 方法中,我从我的 Android 应用程序发送了一个 base64 字符串,我想将该图像上传到 Google Cloud Storage

我用

将字符串解码为 byte[]
byte[] data = Base64.decodeBase64(base64String);

然后我创建一个 Storage 对象来连接它

Storage.Builder storageBuilder = new Storage.Builder(httpTransport,new JacksonFactory(),credential);
Storage storage = storageBuilder.build();

我有存储桶名称和图像名称,但如何将 byte[] 插入存储?

最佳答案

最简单的方法是简单地将您的 byte[] 转换为 InputStream。 Java 正是为此目的提供了 ByteArrayInputStream。

import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.InputStreamContent;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.storage.Storage;
import com.google.api.services.storage.model.StorageObject;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.security.GeneralSecurityException;

public class ByteUploader {

/* Simple function to upload a byte array. */
public static void uploadByteStream(
String bucket, String objectName, byte[] bytes, String contentType) throws Exception {
InputStreamContent contentStream =
new InputStreamContent(contentType, new ByteArrayInputStream(bytes));
StorageObject objectMetadata = new StorageObject().setName(objectName);
Storage.Objects.Insert insertRequest =
getService().objects().insert(bucket, objectMetadata, contentStream);
insertRequest.execute();
}

/* Simple no-auth service */
private static Storage getService() throws IOException, GeneralSecurityException {
HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
return new Storage.Builder(httpTransport, JacksonFactory.getDefaultInstance(), null)
.setApplicationName("myApplication")
.build();
}

public static void main(String[] args) throws Exception {
ByteUploader.uploadByteStream("yarbrough-test", "foobar",new byte[]{0,1,2,3,4}, "text/plain");
}
}

关于android - 将 Base64 字符串上传到 Google Cloud Storage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35215183/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com