Spring MVC解析多部分内容请求

时间:2015-06-11 18:04:57

标签: java spring spring-mvc

我在这个教程上正确https://spring.io/guides/gs/uploading-files/ 并实现了一个多部分文件上传控制器。

然而,坚持得到这个错误:

type Exception report

message Request processing failed; nested exception is java.lang.IllegalArgumentException: Expected MultipartHttpServletRequest: is a MultipartResolver configured?

description The server encountered an internal error that prevented it from fulfilling this request.

以下是控制器的代码,正好来自官方教程:

    package com.springapp.mvc;

    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.bind.annotation.RequestParam;
    import org.springframework.web.bind.annotation.ResponseBody;
    import org.springframework.web.multipart.MultipartFile;

    import java.io.BufferedOutputStream;
    import java.io.File;
    import java.io.FileOutputStream;

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

仅仅是为了获取更多信息,这就是我在angularjs上发送来自前端的请求的方法。请求成功传递:

    Upload.upload({
        url: '/api/items/upload_image',
        file: $file,
        name: $file.name,
        progress: function(e){}
    }).then(function(data, status, headers, config) {
        // file is uploaded successfully
        console.log(data);
    });

我的问题是什么? 包括所有必需的依赖项。

1 个答案:

答案 0 :(得分:0)

这是解决方案: 在pom.xml中包含此依赖项

<!-- Apache Commons FileUpload -->
<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.3.1</version>
</dependency>

<!-- Apache Commons IO -->
<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.4</version>
</dependency>

在配置中添加此bean:     

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