tyczj
tyczj

Reputation: 73916

Upload Base64 string to Google Cloud Storage

In my App Engine method I sent a base64 string from my Android app and I want to upload that image to Google Cloud Storage.

I decode the string to a byte[] with

byte[] data = Base64.decodeBase64(base64String);

Then I create a Storage object to connect to it

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

I have the bucket name and the image name but how do I insert the byte[] into storage?

Upvotes: 1

Views: 2844

Answers (1)

Brandon Yarbrough
Brandon Yarbrough

Reputation: 38389

The easiest way is to simply turn your byte[] into an InputStream. Java provides ByteArrayInputStream for just this purpose.

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");
  }
}

Upvotes: 1

Related Questions