简体   繁体   中英

Uploading Image To Google App Engine Blobstore - Java

I am attempting to upload an image from an Android client to my Google App Engine Blobstore and I am encountering problems. All of the relevant posts I have found use the now deprecated HttpEntity. My code results in my server returning a 500 error.

Android client code:

MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addPart("file", new FileBody(file, ContentType.MULTIPART_FORM_DATA));
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
httppost.setEntity(reqEntity.build());
HttpResponse httpResponse = httpclient.execute(httppost);
String response = EntityUtils.toString(httpResponse.getEntity());

Server (App Engine) code:

public class BlobUpload extends HttpServlet {
  @Override
  private BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();

    public void doPost(HttpServletRequest req, HttpServletResponse res)
      throws ServletException, IOException {

      Map<String, List<BlobKey>> blobs = blobstoreService.getUploads(req);
      BlobKey blobKey = blobs.get("file").get(0);

      res.setStatus(HttpServletResponse.SC_OK);
      res.setContentType("text/plain");

      if (blobKey == null) {
        res.getWriter().print("failure");
      } else {
        res.getWriter().print("success");
      }  
   }
}

I have attempted several other permuatations based on examples I have seen all to no avail. This includes setting the Content-Type to Multipart/Form-Data by adding these lines to my client code:

builder.setBoundary("--theboundary--");
httppost.addHeader("Content-Type", "multipart/form-data; boundary=--theboundary--");

I have tested my servlet to make sure it works so I'm positive the problem lies in the way I'm posting my data to my server. I have scoured the MIME and App Engine docs (both of which I find limited) and can't find a solution. Any thoughts/suggestions or working examples would be greatly appreciated.

As you can see from the Javadoc of getUploads, https://developers.google.com/appengine/docs/java/javadoc/com/google/appengine/api/blobstore/BlobstoreService#getUploads(HttpServletRequest) , it should only be used for request that are the result of createUploadUrl. is that the URL that are you using in "new HttpPost(url);" BTW, did you see how to upload a file from android app to google app engine using GAE (and the comment about using multi-part - see http://evgeny-goldin.com/blog/uploading-files-multipart-post-apache/ )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM