Rami
Rami

Reputation: 2148

How to stream Bitmap from Android to Google App Engine Servlet?

I'm struggling for few days with this problem and you are my last chance solving it.

The Goal:

To upload a bitmap from android client to google app engine and save it in datastore.

Things I have tried:

So I am asking in which dierction I can go from to solve this problem.
Thanks.

Upvotes: 0

Views: 1744

Answers (3)

Guy
Guy

Reputation: 12512

Here is a production tested way:

Use GAE appengine to upload your bitmap to, and serve for future clients.

On the Android code, follow these steps:

  1. Get an Upload URL from GAE
  2. Upload your bitmap to GAE, and get a blobkey back
  3. Later on, use the blobkey to serve the image to your clients.

GAE Servlet code:

getUploadURL:

BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();
String url = blobstoreService.createUploadUrl(path_to_your_upload_servlet);

uploadServlet - stores in blobstore, returns the blobkey to the uploader

BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();
Map<String, List<BlobKey>> uploads = blobstoreService.getUploads(request);
String fileName = uploads.keySet().iterator().next();
final BlobKey blobKey = uploads.get(fileName).get(0);
response.getWriter().println(blobKey.getKeyString());

Android client code:

String uploadUrl = getUrlAsString(..your getUrl servlet path...)
// Upload to GAE (include apache-mime4j.jar and httpmime.jar in your project for this code)
File file = new File(imageFilePath);
HttpPost postRequest = new HttpPost(uploadUrl);
MultipartEntity entity = new MultipartEntity();
entity.addPart("file", new FileBody(file));
postRequest.setEntity(entity);
HttpResponse httpResponse;
HttpClient httpClient = new DefaultHttpClient();
httpClient.getParams().setBooleanParameter("http.protocol.handle-redirects",false);

httpResponse = httpClient.execute(postRequest);
int status = httpResponse.getStatusLine().getStatusCode();
String blobKey = getInputStreamAsString(httpResponse.getEntity().getContent())

Upvotes: 0

Peter Knego
Peter Knego

Reputation: 80340

Few notes:

  1. Do not use Java serialization to transfer data between JVMs. Java serialization is not standardized and is not guaranteed to be compatible between JVMs (or even between versions).

  2. To send binary data it's best to use HTTP POST and set Content-Type appropriately (e.g. application/octet-stream).

So, to make this work do this:

  1. Create a servlet which handles POST and gets the binary data. Use servletRequest.getInputStream() to get hold of binary data.

  2. Use Blobstore FileService API to save data to blobstore.

  3. On Android side use a http client to make a POST request and add your bitmap's binary data to it. If you need to add some metadata use Http headers.

Upvotes: 3

Related Questions