5

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.

1
  • why do you have name="file" on input fields remove that Commented Aug 22, 2015 at 21:05

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

6 Comments

Bro how to identity the image for profile and avatar this gives an array of two images?
instead of files array use two different names when sending formData
This not work avatarImage: $scope.files[0],profileImage:$scope.files[1]
How to use two different names when sending formData?
i am about to update my answer you just handle it , create a viewmodel that contains id,name,profileImage,AvatarImage .
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.