spring mvc中不存在必需的MultipartFile参数'file'

时间:2014-11-24 09:52:51

标签: java image spring spring-mvc file-upload

我正在尝试将上传图片的功能添加到我的spring mvc应用程序中。

jsp part:

...
<form method="POST"  action="uploadImage" enctype="multipart/form-data">
                <div class="load-line">
                    <input type="file" class="file"/>
                    <input type="submit" value="Upload">
...

配置:

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

控制器:

 @RequestMapping(value="/member/createCompany/uploadImage", method=RequestMethod.POST)
    public @ResponseBody String handleFileUpload(
            @RequestParam("file") MultipartFile file){
        String name = "image_name";
        if (!file.isEmpty()) {
            try {
                byte[] bytes = file.getBytes();
                BufferedOutputStream stream =
                        new BufferedOutputStream(new FileOutputStream(new File(name + "-uploaded")));
                stream.write(bytes);
                stream.close();
                return "You successfully uploaded " + name + " into " + name + "-uploaded !";
            } catch (Exception e) {
                return "You failed to upload " + name + " => " + e.getMessage();
            }
        } else {
            return "You failed to upload " + name + " because the file was empty.";
        }
    }

选择图片后,我点击上传并看到错误信息:

HTTP Status 400 - Required MultipartFile parameter 'file' is not present

我错了什么?

3 个答案:

答案 0 :(得分:19)

您尚未指定name属性,@RequestParam("textFile")需要名称

 <input type="file" class="file" name="textFile"/>

答案 1 :(得分:11)

将名称属性添加到&#34;文件&#34;输入标签

<input type="file" class="file" name="file"/>

答案 2 :(得分:0)

对于那些找不到合适解决方案的人,请不要忘记添加

spring.http.multipart.enabled=true

到您的配置文件