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.
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];
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"));
The question is: how do I retrieve and parse the image on my server?
Option 1: Direct File Upload , From this method you can select form-data and set the type to file. Then select an image file by clicking on the button shown in the value column. The content type is automatically detect by postman but if you want you can set it with a relevant MIME type.
Many developers consider it a convenient method for downloading any file type in Python. Once you've imported those files, create a url variable that is set to an input statement asking for the image URL. In the next line of code, implement the get() method from the requests module to retrieve the image.
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.
Servlet 3.0
has support for reading multipart data. MutlipartConfig support in Servlet 3.0
If a servelt is annotated using @MutlipartConfig
annotation, the container is responsible for making the Multipart parts available through
HttpServletRequest.getParts()
HttpServletRequest.getPart("name");
References:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With