Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple File Upload using @Context HttpServletRequest with @FormDataParam in jersey

I have created a jersey restful web service where I managed to upload multiple number of files using @Context HttpServletRequest request as method signature which work nicely.
Thing is, to fetch other form fields I need to repetitively check with .isFormField(); method with relative .getName(); for file or .getFieldName();, and .getString(); method to check whether required fields are present or not every time the web service is called which I think little lengthy and expensive process if there are several other fields.

Easier approach was to use @FormDataParam where webservice used to exposed with parameter which client need to pass but problem is I am not able to upload more than one file at one go.

Since Its also not possible to use request.getParameter("field1"); to get other form fields if media type or enctype is multipart/form-data.

Whenever I tried to combine both @FormDataParam and @Context HttpServletRequest request together, it throws exception:
org.apache.tomcat.util.http.fileupload.FileUploadException: Stream closed
while parsing the request with .parseRequest(request); method of ServletFileUpload class.

Kindly suggest some good approach How can I achieve multiple file upload with getting required form fields as easy as @FormDataParam in jersey.

approach for multiple file upload:

@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.APPLICATION_JSON)
@Path("/multipleFiles")
public String restDemo(@Context HttpServletRequest request) 
{
  //...code goes here
}

My form:

enter image description here

output:(after parsing request)

field1 > abc
field2 > xyz
Chrysanthemum.jpg Size: 879394
Desert.jpg Size: 845941
Hydrangeas.jpg Size: 595284
Jellyfish.jpg Size: 775702

like image 558
A Gupta Avatar asked Jun 18 '13 16:06

A Gupta


1 Answers

If the fields have the same name, like this:

<form name="formtest" action="rest/multipleFiles" method="POST" enctype="multipart/form-data">
    <input type="text" name="atext" value="abc" />
    <input type="text" name="btext" value="123" />
    <input type="file" name="zfile" value="" />
    <input type="file" name="zfile" value="" />
    <input type="submit" value="submit" />
</form>

You can use:

@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.APPLICATION_JSON)
@Path("/multipleFiles")    
public String restDemo(@FormDataParam("zfile") List<FormDataBodyPart> zfile)

Now, I advise against using HttpServletRequest. If you need to process everything, use this:

@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)    
@Produces(MediaType.APPLICATION_JSON)
@Path("/multipleFiles")
public String restDemo(FormDataMultiPart formParams) {
    formParams.getFields();
}
like image 179
Marcos Zolnowski Avatar answered Sep 17 '22 02:09

Marcos Zolnowski