Question

I want to programaticaly download and save image files on Google App Engine. I can see that there is an Datastore API so I can save any object.

Entity e = new Entity("Kind");
e.setProperty("heigh",6);
DatastoreServiceFactory.getDatastoreService().put(e);

But I need to save the downloaded images (byte[]) to somewhere, where I can reference within a HTML context, like src=static/image1.png. This is sounds just like Blobstore.

I have found lots of upload example but I don't want an upload form. So I tried to compile a POST just like in the file upload example, but I doesn't work. Isn't there any easier solution for file saving at Google App Engine (for free so Cloud Storage is not an option)?

URL surl = new URL("http://www.freeonlinegames.com/games/39779/medium.jpg");
byte[] byteArray = URLFetchServiceFactory.getURLFetchService().fetch(surl).getContent();
StringBuilder parameters = new StringBuilder();

parameters.append("--BOUNDARY");
parameters.append("\nContent-Disposition: form-data; name=\"file\"; filename\"test.png\"\n");
parameters.append("Content-Type: image/jpg\n\n");

parameters.append(new String(byteArray));
parameters.append("\n--BOUNDARY\n");

String request = BlobstoreServiceFactory.getBlobstoreService().createUploadUrl("/upload");


URL durl = new URL(request);
log("upload: " + durl.toString());

HttpURLConnection connection = (HttpURLConnection) durl.openConnection();           
connection.setDoOutput(true);
connection.setDoInput(true);

connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=--BOUNDARY");
connection.setRequestProperty("Content-Length",Integer.toString(parameters.toString().getBytes().length));
connection.setRequestProperty("Cache-Control","max-age=0");
                    connection.setRequestProperty("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
connection.setRequestProperty("Accept-Encoding","gzip,deflate,sdch");                   

DataOutputStream wr = new DataOutputStream(connection.getOutputStream ());

wr.writeBytes(parameters.toString());

wr.flush();
wr.close();

BufferedInputStream bis = new BufferedInputStream(connection.getInputStream());
byte[] bkey = new byte[512];
bis.read(bkey);
log("resp: " + new String(bkey));
Was it helpful?

Solution

Free Solution:

  • If the image is less than 1MB, you could store the bytes to datastore.
  • You can always use 3rd party free image hosting solution with API

Paid Solution:

Othewise, Google suggest you to use Google Cloud Storage instead https://cloud.google.com/products/cloud-storage/

As writing to blobstore directly is Deprecated https://developers.google.com/appengine/docs/java/blobstore/#Java_Writing_files_to_the_Blobstore

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top