I want to upload multiple files using angular js, for this I am using FormData() .
Here is my form fields
<input name="profileImage" type="file" class="upload"
onchange="angular.element(this).scope().LoadFileData(this.files)" accept="image/*">
<input name="avatarImage" type="file" class="upload"
onchange="angular.element(this).scope().LoadFileData(this.files)" accept="image/*">
<input name="Id" type="text" ng-model="user.Id" />
<input name="Name" type="text" ng-model="user.Name" />
Here is my Asp.Net MVC controller
public ActionResult AddUser(string user, HttpPostedFileBase[] files)
{
// parse user into User
}
and the angular controller
.controller('formController',['$scope','$http', function ($scope, $http) {
$scope.user = {
Id: 0,
Name: ""
};
$scope.files = [];
$scope.LoadFileData = function(files) {
$scope.files = files;
};
$scope.submit = function() {
$http({
url: "/Home/AddUser",
method: "POST",
headers: { "Content-Type": undefined },
transformRequest: function(data) {
var formData = new FormData();
formData.append("user", angular.toJson(data.user));
for (var i = 0; i < data.files.length; i++) {
formData.append("files[" + i + "]", data.files[i]);
}
return formData;
},
data: { user: $scope.user, files: $scope.files }
})
.success(function(response) { });
};
});
Problem is that I want to upload more than one image one for profile and the other for avatar . When I upload both only the second one shows up which override the previous one . I tried to push $scope.files.push(files) but it gives null.Need help what I am missing there.
Change the LoadFileData
function
$scope.LoadFileData = function (files) {
$scope.files.push(files[0]);
};
files
returns a Filelist object and actual file object is at index 0.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With