Retrieve an Image from a POST request

java, servlets

Solution

Something along the lines of this, using Apache Commons FileUpload:

 // or @SuppressWarnings("unchecked")
 @SuppressWarnings("rawtypes")
 public void doPost(HttpServletRequest request, HttpServletResponse response) 
         throws ServletException, IOException {
     if (ServletFileUpload.isMultipartContent(request)) {
         final FileItemFactory   factory = new DiskFileItemFactory();
         final ServletFileUpload upload  = new ServletFileUpload(factory);

         try {
             final List items = upload.parseRequest(request);

             for (Iterator itr = items.iterator(); itr.hasNext();) {
                 final FileItem item = (FileItem) itr.next();

                 if (!item.isFormField()) {
                    /*
                     * TODO: (for you)
                     *  1. Verify that file item is an image type.
                     *  2. And do whatever you want with it.
                     */
                 }
             }
         } catch (FileUploadException e) {
             e.printStackTrace();
         }
     }
 }

Refer to the `FileItem` API reference doc to determine what to do next.

Problem

I am trying to send a picture to my java servlet (hosted on amazon ec2) to later transfer it to amazon s3 and wonder how to retrieve the Image from the post request. Upload Code The request is sent through iOS RestKit API like this (pic.imageData is a NSData type): ``` RKParams* params = [RKParams params]; [params setValue:pic.dateTaken forParam:@"dateTaken"]; [params setValue:pic.dateUploaded forParam:@"dateUploaded"]; [params setData:pic.imageData MIMEType:@"image/jpeg" forParam:@"image"]; [RKClient sharedClient].username = deviceID; [RKClient sharedClient].password = sessionKey; [RKClient sharedClient].authenticationType = RKRequestAuthenticationTypeHTTPBasic; uploadPictureRequest = [[RKClient sharedClient] post:kUploadPictureServlet params:params delegate:self]; ``` Parsing Code Stub This is how I parse the other 2 parameters on the Java servlet: ``` double dateTaken = Double.parseDouble(req.getParameter("dateTaken")); double dateUploaded = Double.parseDouble(req.getParameter("dateUploaded")); ``` Question The question is: how do I retrieve and parse the image on my server?

Original source