Extract image from POST request

I am trying to send an image to my Java servlet (hosted on amazon ec2) in order to later transfer it to amazon s3 and wonder how to extract the image from the send request.

Download Code

The request is sent via the iOS RestKit API similar to this (pic.imageData is an 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];

Encoding code parsing

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

Question: how to get and analyze the image on my server?

+5
source share
2 answers

Something like that 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 API reference document FileItemto determine what to do next.

+3

Servlet 3.0 . MutlipartConfig Servlet 3.0 @MutlipartConfig, , Multipart

HttpServletRequest.getParts()
HttpServletRequest.getPart("name");

:

+3

All Articles