哪种签名用于弹簧控制器方法

时间:2014-10-06 07:52:22

标签: spring-mvc file-upload

在定义Spring的Controller方法时有很多可能的签名。我很困惑应该使用哪一个以及在哪种情况下使用。 例如,我有以下情况。 我必须将文件上传到服务器,我已经写了一个表格 以下是HTML

<form action="uploadimage?id=${pencil.id}" method="post">
<table border="0">
    <tr>
        <td style="color:maroon;font-weight:bold;">Change/Upload Image</td>
        <td><input type="file" name="image" /></td>
        <td><input type="submit" value="upload" /></td>
        <td><input type="hidden" name="pencilid" value="${pencil.id}" /></td>
    </tr>
</table>
</form>

对于这个我写控制器的方法。在使用@ModelAttribute时,它抛出异常,说不能将bean MaltipartFile实例化为它的接口,并且在使用@RequestParam时返回400错误代码

使用@requestParam

@RequestMapping(value="/uploadimage",method=RequestMethod.POST)
public ModelAndView uploadImage(@RequestParam ("pencilid") String id,@RequestParam("file") MultipartFile file)
{
    System.out.println("In Controller");
    Pencil pencil=null;
    PencilService pencilService=ServiceFactory.getPencilService();
    pencil=pencilService.getPencil(Integer.parseInt(id));
    ModelAndView model= new ModelAndView("pencilview","pencil",pencil);
    model.addObject("id",id);
    //MultipartFile file=(MultipartFile)param.get("image");
    System.out.println(file.getName());
    return model;
}

使用@ModelAttribute

@RequestMapping(value="/uploadimage",method=RequestMethod.POST)
public ModelAndView uploadImage(@ModelAttribute ("pencilid") String id,@ModelAttribute("file") MultipartFile file)
{
    System.out.println("In Controller");
    Pencil pencil=null;
    PencilService pencilService=ServiceFactory.getPencilService();
    pencil=pencilService.getPencil(Integer.parseInt(id));
    ModelAndView model= new ModelAndView("pencilview","pencil",pencil);
    model.addObject("id",id);
    //MultipartFile file=(MultipartFile)param.get("image");
    System.out.println(file.getName());
    return model;
}

请让我知道我在哪里犯错误 在我的Sping-servlet.xml中,我将multipartResolver定义为

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

     <!-- setting maximum upload size -->
    <property name="maxUploadSize" value="100000" />

</bean>

如果需要其他任何内容,请告诉我。

1 个答案:

答案 0 :(得分:0)

我认为您的表单应该具有如下属性的enctype:

 enctype="multipart/form-data"

如果您要上传文件,请使用@RequestParam作为您的文件以及您拥有的其他表单字段,如下所示:

 @RequestMapping(value="/upload", method=RequestMethod.POST)
    public @ResponseBody String handleFileUpload(@RequestParam("name") String name,
            @RequestParam("file") MultipartFile file){

    }

在此示例中来自春天documentationhandleFileUpload采用两个参数,第一个是普通String name,即普通字段,第二个是{{ 1}}这是您要上传的文件。

希望有助于。