Uploading a file to the server directory using Spring MVC

I am trying to upload a file to the server directory from the client machine. I used the following codes:

Fileupload.jsp

<form:form commandName="fileUpload" action="upload.action" method="post" enctype="multipart/form-data"> <form:label path="fileData">Upload a File</form:label> <br /> <form:input type="file" path="fileData" /> <input type="submit" value="upload" > </form:form> 

In my controller:

 @RequestMapping("/upload.action") public String upload(@ModelAttribute("fileUpload") FileUpload fileUpload,HttpServletResponse response,Model model) { CommonsMultipartFile multipartFile = fileUpload.getFileData(); String orginalName = multipartFile.getOriginalFilename(); String filePath = "/my_uploads/"+orginalName; File destination = new File(filePath); String status ="success"; try { multipartFile.transferTo(destination); } catch (IllegalStateException e) { // TODO Auto-generated catch block e.printStackTrace(); status="failure"; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); status="iofailure"; } model.addAttribute("status", status); return "home"; } 

FileUpload.java:

 { private CommonsMultipartFile fileData; .... } 

NullPointerException throws a string String orginalName = multipartFile.getOriginalFilename(); .. what I did wrong?

+4
source share
2 answers

Try adding MultipartFile as a parameter in the request handler.

 @RequestMapping("/upload.action") public String upload(@RequestParam(value = "file") MultipartFile file, HttpServletResponse response,Model model) { //Controller logic... } 

This will require registering a new bean in the dispatcher configuration.

 <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="maxUploadSize" value="5000000"/> </bean> 
+6
source
 @RequestMapping("/upload.action") public String upload(@RequestParam("fileData") MultipartFile file, HttpServletResponse response,Model model) { //Controller logic... } 

you must have the same name in the parameter for your request handler method, regardless of what you specified in FileUpload Pojo for multipartFile ("fileData"), it should be in the parameter

Thanks,

0
source

All Articles