无法使用Angular和Spring Boot上传文件

时间:2015-01-26 12:50:47

标签: java angularjs spring

我尝试使用AngularJS和Spring Boot控制器上传文件。我有两个问题:

1)当我使用HTML表单时,提交' 我超出了尺寸,即使我已将文件的最大尺寸设置为128M。代码如下所示:

public class AppConfig {
    @Bean
    public MultipartConfigElement multipartConfigElement() {
        factory.setMaxFileSize("128MB");
        factory.setMaxRequestSize("128MB");
        return factory.createMultipartConfig();
    }
}

Spring似乎忽略了这些设置。

2)当我尝试上传文件时,收到错误:

org.springframework.web.multipart.MultipartException: The current request is not a multipart request

Angular控制器如下所示:

 $scope.uploadFile=function(){
     var formData=new FormData();
     formData.append("file",file.files[0]);

     $http.post('/content-files/upload /',  file.files[0], {

         transformRequest: function(data, headersGetterFunction) {
                return data; // do nothing! FormData is very good!
            },
         headers: {'Content-Type': undefined }

     })
     .success(function(){
         console.log('Post Succeded !');
     })
     .error(function(){
         console.log('Post Failed .');
     });
}

,Spring控制器如下所示:

@RequestMapping(value = "/content-files/upload/", method = RequestMethod.POST  )           
public @ResponseBody String handleFileUpload(  @RequestParam("file") MultipartFile file) {
    System.out.println("BrandController.uploadMultipart()");

    String name=file.getName();
    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.";
    }
}

我尝试将JS控制器更改为:

$http.post('/content-files/upload /',  file.files[0], {         
    headers: { 'Content-Type': undefined },
    transformRequest: angular.identity
})

但是我得到了与上面相同的错误。当我尝试将JS控制器更改为:

headers: { 'Content-Type': 'multipart/form-data' },
          transformRequest: angular.identity

我收到错误the request was rejected because no multipart boundary was found

似乎我已经尝试了所有参数组合,但仍然无效。要使此文件上传起作用,我需要做什么?

2 个答案:

答案 0 :(得分:2)

试试这个:

var formData = new FormData();
formData.append('file',file.files[0]);

$http.post('/content-files/upload /',  formData, {         
    headers: { 'Content-Type': undefined },
    transformRequest: angular.identity
})

答案 1 :(得分:0)

基于MultipartAutoConfiguration代码,使用Spring Boot增加上传大小限制(默认最大值为1 MB)的方法是以下属性:

multipart.maxFileSize=129Mb
multipart.maxRequestSize=129Mb

关于jquery分段上传,你的方式看起来不正确,你可以检查其他好的引用,我在Stackoverflow本身看到了很多。