Search code examples
javaspringspring-mvcservletsspring-web

How to upload file in spring?


I am not able to get the file name in spring controller

<form:form method="post" modelAttribute="sampleDetails" 
 enctype="multipart/form-data">
    <input type="file" name="uploadedFileName" id="fileToUpload" required="" >
    <input type="submit" name="import_file" value="Import File" id="" />
</form:form>

Its my post method in controller

@RequestMapping(method = RequestMethod.POST)
public String importQuestion(@Valid @RequestParam("uploadedFileName") 
MultipartFile multipart, @ModelAttribute("sampleDetails") SampleDocumentPojo sampleDocument,  BindingResult result, ModelMap model) {
    logger.debug("Post method of uploaded Questions ");

    logger.debug("Uploaded file Name : " + multipart.getName());
    return "importQuestion";
}

After submit get the warning message.

 warning [http-nio-8080-exec-9] WARN 
 org.springframework.web.servlet.PageNotFound - Request method 'POST' not 
 supported
 [http-nio-8080-exec-9] WARN 
 org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver 
 - Handler execution resulted in exception: Request method 'POST' not 
 supported

Solution

  • in your controller you need to specify that you are expecting mutlipart

    using

    consumes = {"multipart/form-data"}
    

    and to ge the file name using getOriginalFileName()

    @RequestMapping(method = RequestMethod.POST, consumes = {"multipart/form-data"})
    public String importQuestion(@Valid @RequestParam("uploadedFileName") 
    MultipartFile multipart,  BindingResult result, ModelMap model) {
       logger.debug("Post method of uploaded Questions ");
    
        logger.debug("Uploaded file Name : " + multipart.getOriginalFilename());
       return "importQuestion";
    }
    

    Also in your html the name of your input of type file should be the same as the RequestParam "uploadedFileName"

         <input type="file" name="uploadFileName" id="fileToUpload" required="" >
    

    change it to

      <input type="file" name="uploadedFileName" id="fileToUpload" required="" >