Santosh Jadi Santosh Jadi - 7 months ago 23
Java Question

Get selected image to Controller Class with enctype="multipart/form-data"?

JSP page:

<form action="addUpdateSchool" method="post" enctype="multipart/form-data">
<table align="center">
<tr>
<td>School Name :</td>
<td><input type="text" id="school_name" name="school_name" /></td>
</tr>
<tr>
<td>Address :</td>
<td><textarea rows="4" cols="30" id="address" name="address"></textarea> </td>
</tr>
<tr>
<td>Logo :</td>
<td><input type="file" id="logo" name="logo"/></td>
</tr>
<tr>
<td><input type="submit" onclick="return validation();" /></td>
</tr>
</table>
</form>


I'm trying to get all above form properties at the Controller class including logo, but its showing null.

How can i resolve it?

Controller Class:

@RequestMapping(value = "/addSchool", method = RequestMethod.POST)
public String addSchool(@ModelAttribute SchoolModel schoolModel, HttpSession session) {

System.out.println("name: "+schoolModel.getSchool_name);

}

Answer

dispatcher-servlet.xml

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <property name="maxUploadSize" value="10000000" /> <!-- setting maximum upload size -->
</bean>

Controller Class:

@RequestMapping(value = "/addUpdateSchool", method = RequestMethod.POST)
public String addSchool(@RequestParam("logo") MultipartFile multipartFile, @ModelAttribute SchoolModel schoolModel) {
    String path="";
    try{
        MultipartFile file = multipartFile;
        if(file.getOriginalFilename().trim().length()>0) {
            path=saveFile(file, multipartFile.getOriginalFilename());
        }else{
            path="";
        }
        System.out.println("path: "+path);
    }catch(Exception e){
        e.printStackTrace();
    }
}

public static String saveFile(MultipartFile file, String name) throws IOException{
    byte[] bytes = file.getBytes();
    Random random = new Random();       
    File dir = new File("D:\WebSLCMImages\WebSLCM\"); // Path to Save Image
    if (!dir.exists()){
        dir.mkdirs();
    }
    String path = dir+"/" + getFileName(name) + System.currentTimeMillis() + Math.abs(random.nextInt())+ getFileExtension(name);
    File serverFile = new File(path);
    BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile));
    stream.write(bytes);
    stream.close();
    return path;
}

Note: Don't forget to add related jar files (commons-fileupload-1.3.jar)

Reference link: MVC-Multipart-Resolver

Comments