将Base64字符串上传到Google云端存储
问题描述:
在我的App Engine方法中,我从Android应用发送了一个base64 string
,我想将该图像上传到Google Cloud Storage
。将Base64字符串上传到Google云端存储
我
byte[] data = Base64.decodeBase64(base64String);
然后解码字符串到byte[]
我创建了一个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");
}
}
'Insert'对象没有'setContent()'只有'setContentType()'。这些例子也可能过时了,因为'storage.objects()。insert'不再接受InputStream,只接受'AbstractInputStreamContent' – tyczj
嘿,刚回到我的办公桌。这是一个新版本,实际上,你知道,它的作品。 –
另一个快速问题,如果你在输入流上设置它,你是否需要在'StorageObject'上设置内容类型? – tyczj