How to upload Files along with Form Data using Angularjs?
I am working on a UI that is built in AngularJs. It has a form where users put their details like Id, Name, Address, PIN etc. Along with that I have to provide a functionality where users can upload multiple files along with the FormData.
I have gone through the tutorials for File Upload in AngularJs and I've created a directive for uploading file.
The code in JavaScript looks like this,
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},
});
In Spring MVC the controller looks like,
@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 contains,
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;
}
When I try to execute this I get
415 (Unsupported Media Type)
I can make this work using @RequestParam
for each variable. But is there a way by which I can get the Form Data in Resource object and File in a separate parameter?