Search code examples
javafilespring-mvcapache-commons-fileupload

Multiple Files upload in spring mvc


I am trying to upload multiple files using spring mvc and commons-fileupload*.jar. I am using HttpServletRequest for getting the request object and then request.getPart() to get file part. But when I run the code I found below error.

java.lang.IllegalStateException: Unable to process parts as no multi-part configuration has been provided

the code is as below:

public ModelAndView uploadCon(@RequestParam Map<String,String> map, HttpServletRequest request)
{
    Part part1=request.getPart("wallpaper0");
    Part part2=request.getPart("wallpaperx");
    //then write these files 
}

the spring-servlet.xml file has the bean defined as below:

<bean id="multipartResolver"  class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/>

Solution

  • Here is the sample

    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public @ResponseBody
    ResponseEntity<Map<String, Object>> handleFileUpload(
            @RequestParam("file1") MultipartFile file1,
            @RequestParam("file2") MultipartFile file2) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("status", "failure");
        try {
            if (!file1.isEmpty() && !file2.isEmpty()) {
    
                // get the files here
    
                map.put("status", "success");
            }
        } catch (Exception e) {
            LOGGER.severe(e.toString());
        }
    
        ResponseEntity<Map<String, Object>> responseEntity = new ResponseEntity<Map<String, Object>>(
                map, HttpStatus.OK);
    
        return responseEntity;
    }
    

    and make sure that you have added

    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
                <property name="maxUploadSize" value="50000000"/>
    </bean>
    

    in your spring.xml file.

    Or refer this sample if you want to get a list of files as List<MultipartFile>.