I\'m trying to upload aN image to google cloud storage.
I found an example like this https://github.com/pliablematter/simple-cloud-storage that explains how to do that.<
public class RetrieveFeedTask extends AsyncTask {
private Exception exception;
protected String doInBackground(Void... params) {
JsonFactory jsonFactory = new JacksonFactory();
try {
List scopes = new ArrayList();
scopes.add(StorageScopes.DEVSTORAGE_FULL_CONTROL);
HttpTransport httpTransport = new com.google.api.client.http.javanet.NetHttpTransport();
//convert key into class File. from inputstream to file. in an aux class.
File file =getTempPkc12File();
//Google Credentianls
GoogleCredential credential = new GoogleCredential.Builder().setTransport(httpTransport)
.setJsonFactory(jsonFactory)
.setServiceAccountId("xxxxxx-xxxx-xxx@xxxxx-xxxxxx.iam.gserviceaccount.com")
.setServiceAccountScopes((scopes))
.setServiceAccountPrivateKeyFromP12File(file)
.build();
String URI = "https://storage.googleapis.com/" + GOOGLE_STORAGE_BUCKET+"/images/"+createImageFile();
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.
Resources res = getResources();
Drawable drawable = res.getDrawable(R.drawable.camera);
Bitmap bitmap = ((BitmapDrawable)drawable).getBitmap();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] bitMapData = stream.toByteArray();
HttpContent contentsend = new ByteArrayContent("image/jpeg", bitMapData );
HttpRequest putRequest;
putRequest = requestFactory.buildPutRequest(url, contentsend);
com.google.api.client.http.HttpResponse response = putRequest.execute();
String content = response.parseAsString();
Log.i("debug", "response is:"+response.getStatusCode());
Log.i("debug", "response content is:"+content);
} catch (IOException | GeneralSecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.i("ErrorUpload",""+e.toString());
}
return "";
}
protected void onPostExecute(String feed) {
int i = 0;
int j = i;
// TODO: check this.exception
// TODO: do something with the feed
Log.i("OnPost",""+feed);
}
}
private File getTempPkc12File() throws IOException {
// xxx.p12 export from google API console
InputStream pkc12Stream = (NewProduceInfo.this).getResources().getAssets().open("xxxxx-xxxxxxx-xxxxxx.p12");
File tempPkc12File = File.createTempFile("temp_pkc12_file", "p12");
OutputStream tempFileStream = new FileOutputStream(tempPkc12File);
int read = 0;
byte[] bytes = new byte[1024];
while ((read = pkc12Stream.read(bytes)) != -1) {
tempFileStream.write(bytes, 0, read);
}
return tempPkc12File;
}