Spring mvc当前请求不是多部分请求

时间:2016-06-11 02:48:33

标签: java spring spring-mvc file-upload

每当我尝试访问“/ uploadFile”时,我总会收到此错误

Etat HTTP 500 - Request processing failed; nested exception is org.springframework.web.multipart.MultipartException: The current request is not a multipart request

这是控制器中的方法

@RequestMapping(value = "/uploadFile", method = RequestMethod.GET)
    public @ResponseBody
    String uploadFileHandler(String name,MultipartFile file) {

        if (!file.isEmpty()) {
            try {
                byte[] bytes = file.getBytes();

                // Creating the directory to store file
                String rootPath = System.getProperty("catalina.home");
                File dir = new File(rootPath + File.separator + "tmpFiles");
                if (!dir.exists())
                    dir.mkdirs();

                // Create the file on server
                File serverFile = new File(dir.getAbsolutePath()
                        + File.separator + name);
                BufferedOutputStream stream = new BufferedOutputStream(
                        new FileOutputStream(serverFile));
                stream.write(bytes);
                stream.close();

                logger.info("Server File Location="
                        + serverFile.getAbsolutePath());

                return "You successfully uploaded file=" + name;
            } catch (Exception e) {
                return "You failed to upload " + name + " => " + e.getMessage();
            }
        } else {
            return "You failed to upload " + name
                    + " because the file was empty.";
        }
    }

jsp表单

<form method="GET" action="uploadFile" enctype="multipart/form-data">
    File to upload: <input type="file" name="file"><br /> 
    Name: <input type="text" name="name"><br /> <br /> 
    <input type="submit" value="Upload"> Press here to upload the file!
</form>

我把它添加到web.xml

<listener>
        <listener-class>org.springframework.web.multipart.commons.CommonsMultipartResolver</listener-class>
    </listener>

我在这里做错了什么?非常感谢任何帮助。

2 个答案:

答案 0 :(得分:0)

@RequestMapping(...., consumes = {"multipart/*"})

指定*或保留*

答案 1 :(得分:0)

上传文件http我的必须是application / form-data方法必须发布

 <form method="POST"
 method = RequestMethod.POST