I want to upload image on Google Cloud Storage
from my android app. For that I searched and found that GCS JSON Api
provides this feature. I did a lot of research for Android sample which demonstrates its use. On the developer site they have provided code example that only support java. I don't know how to use that API in Android. I referred this and this links but couldn't get much idea. Please guide me on how i can use this api with android app.
-
Did u find something? @zanky ? – chelo_c May 05 '14 at 22:50
-
1@chelo_c No, instead of that i am using `Blobstore` to store image on Google Cloud. – Zankhna May 06 '14 at 04:32
2 Answers
Ok guys so I solved it and got my images being uploaded in Cloud Storage all good. This is how:
Note: I used the XML API it is pretty much the same.
First, you will need to download a lot of libraries. The easiest way to do this is create a maven project and let it download all the dependencies required. From this sample project : Sample Project The libraries should be:
Second, you must be familiar with Cloud Storage using the api console You must create a project, create a bucket, give the bucket permissions, etc. You can find more details about that here
Third, once you have all those things ready it is time to start coding. Lets say we want to upload an image: Cloud storage works with OAuth, that means you must be an authenticated user to use the API. For that the best way is to authorize using Service Accounts. Dont worry about it, the only thing you need to do is in the API console get a service account like this:
We will use this service account on our code.
Fourth, lets write some code, lets say upload an image to cloud storage. For this code to work you must put your key generated in step 3 in assets folder, i named it "key.p12".
I don't recommend you to do this on your production version, since you will be giving out your key.
try{
httpTransport= new com.google.api.client.http.javanet.NetHttpTransport();
//agarro la key y la convierto en un file
AssetManager am = context.getAssets();
InputStream inputStream = am.open("key.p12"); //you should not put the key in assets in prod version.
//convert key into class File. from inputstream to file. in an aux class.
File file = UserProfileImageUploadHelper.createFileFromInputStream(inputStream,context);
//Google Credentianls
GoogleCredential credential = new GoogleCredential.Builder().setTransport(httpTransport)
.setJsonFactory(JSON_FACTORY)
.setServiceAccountId(SERVICE_ACCOUNT_EMAIL)
.setServiceAccountScopes(Collections.singleton(STORAGE_SCOPE))
.setServiceAccountPrivateKeyFromP12File(file)
.build();
String URI = "https://storage.googleapis.com/" + BUCKET_NAME+"/"+imagename+".jpg";
HttpRequestFactory requestFactory = httpTransport.createRequestFactory(credential);
GenericUrl url = new GenericUrl(URI);
//byte array holds the data, in this case the image i want to upload in bytes.
HttpContent contentsend = new ByteArrayContent("image/jpeg", byteArray );
HttpRequest putRequest = requestFactory.buildPutRequest(url, contentsend);
com.google.api.client.http.HttpResponse response = putRequest.execute();
String content = response.parseAsString();
Log.d("debug", "response is:"+response.getStatusCode());
Log.d("debug", "response content is:"+content);} catch (Exception e) Log.d("debug", "Error in user profile image uploading", e);}
This will upload the image to your cloud bucket.
For more info on the api check this link Cloud XML API

- 1,739
- 3
- 21
- 34
-
if not in assets where shoud i put the p12 key in production version? thanks – Cristiana Chavez Jul 24 '14 at 10:51
-
@Cristiana214 im still not in production so I have not tjought about that. But the problem is that if you give out the p12 key somebody else will be able to acess the api. – chelo_c Jul 24 '14 at 15:53
-
can you please give all code ? i don't know for example what is JSON_FACTORY, STORAGE_SCOPE ... ? – tamtoum1987 Apr 08 '15 at 13:48
-
@tamtoum1987 that is not my code you are asking, that comes with the dependencies. – chelo_c Apr 08 '15 at 18:08
-
@chelo_c what dependence please ? i'm not using maven in android, can i find source code in maven dependencie ? – tamtoum1987 Apr 08 '15 at 18:18
-
@tamtoum1987 it says: "First, you will need to download a lot of libraries. The easiest way to do this is create a maven project and let it download all the dependencies required." Have you done this step? – chelo_c Apr 09 '15 at 01:35
-
I avoid using Maven because it's cause me a lot of problem when trying to build with ant anyway i resolve the problem now i can upload images to google storage i post solution here: http://stackoverflow.com/questions/29509335/upload-image-to-google-cloud-storage-with-an-application-android/29532738#29532738 – tamtoum1987 Apr 09 '15 at 07:48
-
-
UserProfileImageUploadHelper is not recognised. which is the jar file specific to this class? – Jana Sep 23 '16 at 09:48
-
cannot resolve symbol "UserProfileImageUploadHelper" . how to resolve it? – Jana Sep 26 '16 at 07:28
Firstly, You should get the below information by registering your application in the GCP console.
private final String pkcsFile = "xxx.json";//private key file
private final String bucketName = "your_gcp_bucket_name";
private final String projectId = "your_gcp_project_id";
Once you get the credentials, you should put the private key (.p12 or .json) in your assets folder. I'm using JSON format private key file. Also, you should update the image location to upload.
@RequiresApi(api = Build.VERSION_CODES.O)
public void uploadImageFile(String srcFileName, String newName) {
Storage storage = getStorage();
File file = new File(srcFileName);//Your image loaction
byte[] fileContent;
try {
fileContent = Files.readAllBytes(file.toPath());
} catch (IOException e) {
e.printStackTrace();
return;
}
if (fileContent == null || fileContent.length == 0)
return;
BlobInfo.Builder newBuilder = Blob.newBuilder(BucketInfo.of(bucketName), newName);
BlobInfo blobInfo = newBuilder.setContentType("image/png").build();
Blob blob = storage.create(blobInfo, fileContent);
String bucket = blob.getBucket();
String contentType = blob.getContentType();
Log.e("TAG", "Upload File: " + contentType);
Log.e("File ", srcFileName + " uploaded to bucket " + bucket + " as " + newName);
}
private Storage getStorage() {
InputStream credentialsStream;
Credentials credentials;
try {
credentialsStream = mContext.getAssets().open(pkcsFile);
credentials = GoogleCredentials.fromStream(credentialsStream);
} catch (IOException e) {
e.printStackTrace();
return null;
}
return StorageOptions.newBuilder()
.setProjectId(projectId).setCredentials(credentials)
.build().getService();
}

- 669
- 1
- 9
- 26