使用enctype =" multipart / form-data"?将所选图像输入到控制器类

时间:2016-02-15 09:43:26

标签: java jsp spring-mvc file-upload multipartform-data

JSP:

<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>

我试图在控制器类中获取所有上述表单属性,包括徽标,但它显示为null。

我该如何解决?

控制器类:

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

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

} 

2 个答案:

答案 0 :(得分:1)

您必须在应用程序上下文中添加multipartResolver才能在视图页面中处理enctype="multipart/form-data"。 在应用程序contex xml文件中添加以下内容

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

并在类路径中添加相应的jar文件。

有关详细信息,请参阅spring here

中的文档

答案 1 :(得分:0)

<强>调度-servlet.xml中

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

控制器类:

@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;
}

注意:不要忘记添加相关的jar文件(commons-fileupload-1.3.jar)

参考链接: MVC-Multipart-Resolver