【问题标题】:Upload Base64 string to Google Cloud Storage将 Base64 字符串上传到 Google Cloud Storage
【发布时间】:2016-02-05 02:11:05
【问题描述】:

在我的 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();

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

【问题讨论】:

    标签: android google-app-engine google-cloud-storage


    【解决方案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");
      }
    }
    

    【讨论】:

    • Insert 对象没有setContent(),只有setContentType()。这些示例也可能已过时,因为 storage.objects().insert 不再接受 Inputstream 并且只接受 AbstractInputStreamContent
    • 嘿,刚回到我的办公桌。这是一个新版本,你知道,它确实有效。
    • 另一个小问题,如果您在输入流上设置内容类型,您是否需要在 StorageObject 上设置内容类型?
    • 我希望如果您将其排除在元数据之外,它可能会起作用。
    • @BrandonYarbrough 请在 python 中添加相同问题的代码。
    猜你喜欢
    • 2019-01-11
    • 2017-08-10
    • 1970-01-01
    • 2020-08-28
    • 1970-01-01
    • 2017-08-11
    • 2018-12-23
    • 1970-01-01
    • 2015-09-09
    相关资源
    最近更新 更多