gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 05:02:22 24 4
gpt4 key购买 nike

我正在尝试使用 AngularJS 和 Spring Boot Controller 上传文件。我有两个问题:

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 Controller 如下所示:

 $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 Controller 如下所示:

@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 Controller 更改为:

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

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

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

我收到错误请求被拒绝,因为未找到多部分边界

似乎我已经尝试了所有参数组合,但仍然没有效果。我需要做什么才能让此文件上传正常工作?

最佳答案

试试这个:

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

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

关于java - 无法使用 Angular 和 Spring Boot 上传文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28150458/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com