在我的App Engine方法中,我从Android应用发送了base64 string
,我想将该图片上传到Google Cloud Storage
。
我使用
将字符串解码为byte[]
byte[] data = Base64.decodeBase64(base64String);
然后我创建一个Storage
对象来连接它
Storage.Builder storageBuilder = new Storage.Builder(httpTransport,new JacksonFactory(),credential);
Storage storage = storageBuilder.build();
我有存储桶名称和图像名称,但如何将字节[]插入存储?
答案 0 :(得分:1)
最简单的方法是将您的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");
}
}