[英]Cannot upload file using Angular and Spring Boot
我正在尝试使用AngularJS和Spring Boot控制器上传文件。 我有2个问题:
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
。
似乎我已经尝试了所有带参数的组合,但仍然无济于事。 我需要怎么做才能使该文件上传正常工作?
试试这个:
var formData = new FormData();
formData.append('file',file.files[0]);
$http.post('/content-files/upload /', formData, {
headers: { 'Content-Type': undefined },
transformRequest: angular.identity
})
基于MultipartAutoConfiguration代码,使用Spring Boot增加上载大小限制(默认最大为1 MB)的方法具有以下属性:
multipart.maxFileSize=129Mb
multipart.maxRequestSize=129Mb
关于jquery分段上传,您的执行方式似乎不正确,还有其他可以参考的良好参考,我在Stackoverflow本身中已经看到了很多。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.