我正在开发一个在AngularJs中构建的UI。它有一个表单,用户可以在其中输入ID,姓名,地址,PIN等详细信息。除此之外,我还必须提供一种功能,用户可以使用FormData上传多个文件。
我已经浏览了AngularJs中的文件上传教程,并且我已经创建了一个上传文件的指令。
JavaScript中的代码如下所示,
var formData = new FormData();
formData.append('id', $scope.id);
formData.append('name', $scope.name);
formData.append('addressLine1', $scope.addressLine1);
formData.append('addressLine2', $scope.addressLine2);
formData.append('road', $scope.road);
formData.append('city', $scope.city);
formData.append('pin', $scope.pin);
formData.append('state', $scope.state);
formData.append('country', $scope.country);
formData.append('file', $scope.file);
$http({
method: 'POST',
url: baseURL + "item/" + $scope.id,
data: formData,
responseType: 'arraybuffer',
transformRequest: angular.identity,
headers: {'Content-Type': undefined},
});
在Spring MVC中,控制器看起来像,
@RequestMapping(value = "item/{id}", method = RequestMethod.POST,
consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public @ResponseBody ResponseResource addData(@PathVariable String id,
@RequestParam DataRequestResource dataRequestResource,
@RequestParam(value = "file") MultipartFile file){
DataRequestResource包含,
public class DataRequestResource {
private String id;
private String name;
private String addressLine1;
private String addressLine2;
private Long road;
private String city;
private String pin;
private String state;
private String country;
}
当我尝试执行此操作时,我得到了
415 (Unsupported Media Type)
我可以使用@RequestParam
为每个变量做这项工作。但有没有办法让我在Resource对象和File中获取Form Data在一个单独的参数中?
答案 0 :(得分:0)
var data = new FormData();
for (var i = 0; i < files.length; i++) {
data.append("Photo",files[i]);
}
data.append('description',description);
$http.post('/api/timeline/submit_post',data,{
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
}).then(function(response){
var res = response.data;
if(res.status == "Success"){
$scope.$emit('hide_loader');
$scope.$parent.posts = [];
$scope.$parent.time = Date.now()/1000;
$scope.$parent.getAllPostOfTimeline();
toaster.pop('success', 'Post uploaded successfully.');
$scope.description = '';
$scope.modal.close();
}else{
$scope.$emit('hide_loader');
toaster.pop("error",res.msg);
}
},function(err){
$scope.$emit('hide_loader');
toaster.pop("error","Server");
});