Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Upload multiple files with FormData using AngularJS and Asp.Net MVC

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.

like image 864
Ghazanfar Khan Avatar asked Nov 09 '22 06:11

Ghazanfar Khan


1 Answers

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.

like image 165
MstfAsan Avatar answered Nov 14 '22 22:11

MstfAsan