title: How to write file on Google App Engine?
body: <p>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.</p>
  
  <pre><code>Entity e = new Entity("Kind");
  e.setProperty("heigh",6);
  DatastoreServiceFactory.getDatastoreService().put(e);
  </code></pre>
  
  <p>But I need to save the downloaded images (byte[]) to somewhere, where I can reference within a HTML context, like <code>src=static/image1.png</code>. This is sounds just like Blobstore.</p>
  
  <p>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 <a href="https://developers.google.com/appengine/docs/java/blobstore/#Java_Uploading_a_blob" rel="nofollow">upload example</a>, 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)?</p>
  
  <pre><code>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));
  </code></pre>