I am converting a Java web application into a Spring framework and appreciate some tips on the issues that I have to deal with when downloading files. The source code was written using org.apache.commons.fileupload.
Can Spring MultipartFile wrap org.apache.commons.fileupload or can I exclude this dependency from my POM file?
I saw the following example:
@RequestMapping(value = "/form", method = RequestMethod.POST)
public String handleFormUpload(@RequestParam("file") MultipartFile file) {
if (!file.isEmpty()) {
byte[] bytes = file.getBytes();
return "redirect:uploadSuccess";
} else {
return "redirect:uploadFailure";
}
}
Initially, I tried to follow this example, but always got an error, because I could not find this query parameter. So, in my controller, I did the following:
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public @ResponseBody
ExtResponse upload(HttpServletRequest request, HttpServletResponse response)
{
ExtResponse extResponse = new ExtResponse();
try {
if (request instanceof MultipartHttpServletRequest)
{
MultipartHttpServletRequest multipartRequest =
(MultipartHttpServletRequest) request;
MultipartFile file = multipartRequest.getFiles("file");
InputStream input = file.getInputStream();
extResponse.setSuccess(true);
}
} catch (Exception e) {
extResponse.setSuccess(false);
extResponse.setMessage(e.getMessage());
}
return extResponse;
}
and it works. If someone tells me why @RequestParam does not work for me, I would appreciate it. BTW I have
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="2097152"/>
</bean>
in my servlet context file.
source
share