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:
output:(after parsing request)
field1 > abc
field2 > xyz
Chrysanthemum.jpg Size: 879394
Desert.jpg Size: 845941
Hydrangeas.jpg Size: 595284
Jellyfish.jpg Size: 775702
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();
}
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