Hei
Hei

Reputation: 513

Spring 3.0 handling file upload issue

I am using Spring MVC 3.0 for file upload, I have followed several online tutorial on how to upload file using spring. However, I keep failing on getting my file, it is always null when the form is being submitted.

Please find my codes below:

View:

<form:form  action="processXML" modelAttribute="uploadXML" method="post" enctype="multipart/form-data">
<div>
    <table>
        <tr>
            <td>
                <input name="uploadXML" type="file"/>
            </td>
        </tr>
    </table>
    <input type="submit"/>
</div>

Controller:

@RequestMapping(value="processXML", method = RequestMethod.POST)
public ModelAndView processXML(@ModelAttribute("uploadXML") UploadXML uploadXML, ModelMap model) {

    logger.info("Start processing import file.");

    ModelAndView modelAndView = new ModelAndView("import");
    //modelAndView.addObject("courseId", courseId);

    logger.info("Data: " + uploadXML.getFile().getName());
    logger.info("Data 2: " + uploadXML.getFile().getContentType());
    logger.info("Data 3: " + uploadXML.getFile().getSize());


    return modelAndView;
}

UploadXML.java

public class UploadXML {

private MultipartFile file;

public MultipartFile getFile() {
    return file;
}

public void setFile(MultipartFile file) {
    this.file = file;
}

}

I have also included:

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

into my servlet.xml.

Could anyone give me some helps?

Thanks so much!

Upvotes: 0

Views: 606

Answers (1)

Rajesh
Rajesh

Reputation: 3034

Try this basic example first

  <form:form  action="processXML"  method="post" enctype="multipart/form-data">
        <div>
            <table>
                <tr>
                    <td>
                        <input name="uploadXMLFile" type="file"/>
                    </td>
                </tr>
            </table>
            <input type="submit"/>
        </div>
</form:form>

@RequestMapping(value="processXML", method = RequestMethod.POST)
public ModelAndView processXML(@RequestParam("uploadXMLFile") CommonsMultipartFile file, ModelMap model) {

    logger.info("Start processing import file.");

    ModelAndView modelAndView = new ModelAndView("import");
    //modelAndView.addObject("courseId", courseId);

    logger.info("Data: " + file.getName());

    logger.info("Data 3: " + file.getSize());


    return modelAndView;
}

Upvotes: 1

Related Questions