Santosh Jadi Santosh Jadi - 2 years ago 85
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">
<td>School Name :</td>
<td><input type="text" id="school_name" name="school_name" /></td>
<td>Address :</td>
<td><textarea rows="4" cols="30" id="address" name="address"></textarea> </td>
<td>Logo :</td>
<td><input type="file" id="logo" name="logo"/></td>
<td><input type="submit" onclick="return validation();" /></td>

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 Source


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

Controller Class:

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

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()){
    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));
    return path;

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

Reference link: MVC-Multipart-Resolver

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download