如何从spring mvc中的angular multipart / form数据请求中检索文件

时间:2016-01-11 19:47:01

标签: java angularjs spring spring-mvc

我使用ngFileUpload指令将数据发送到客户端:

$scope.upload = function (dataUrl, formValid) {
                if (formValid && formValid === true) {
                    console.log($scope.user);
                    Upload.upload({
                        url: 'http://localhost:8080/user/',
                        data: $scope.setPhotoAndReturnUser(Upload.dataUrltoBlob(dataUrl))
                   .......
$scope.setPhotoAndReturnUser = function (photo) {
                $scope.user.photo.image = photo;
                return $scope.user;
            };

用户对象包含其他用户信息用户名,电子邮件等。 这就是请求的样子:

enter image description here

@RestController
@RequestMapping("/user")
public class UserRestController {
      @RequestMapping(method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
                public ResponseEntity newUser(HttpServletRequest request) {
                    MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) request;
                    UserDTO user = new UserDTO(mRequest);
                    if (service.validate(user)) {
                        registrationService.register(user, request);
                        return new ResponseEntity(HttpStatus.NO_CONTENT);
                    }
                    return new ResponseEntity(HttpStatus.BAD_REQUEST);
            }

我的域名转移对象构造函数:

 public UserDTO(MultipartHttpServletRequest request) {
                this.userEmail = request.getParameter("userEmail");
                this.userName = request.getParameter("userName");
                this.userPass = request.getParameter("userPass");

这是我得到的例外:

  

引起:java.lang.NoClassDefFoundError:   COM / fasterxml /杰克逊/注解/ JsonProperty $访问

我的多部分解析器配置:

@Bean
    MultipartResolver multipartResolver() {
        CommonsMultipartResolver resolver = new CommonsMultipartResolver();
        resolver.setMaxUploadSize(1000000);
        return resolver;
    }

我用: 杰克逊核心2.4.6 jackson-databind:2.6.4

但我无法完全理解发生了什么,我的方法参数中没有任何域对象,并且根据开发人员工具,请求被编码为多部分/表单数据。我应该尝试使用Spring匿名身份验证,并将注册过程分成两个不同的请求吗?

1 个答案:

答案 0 :(得分:0)

问题在于请求参数的命名错误,我必须这样做,而不是将所有数据作为一个对象发送:

Upload.upload({
                        url: 'http://localhost:8080/user/',
                        file:Upload.dataUrltoBlob(dataUrl)
                        fields: {...}

我的maven依赖性也有问题,对于春季4推荐的jackson libery是

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.3.3</version>
        </dependency>