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

£可爱£侵袭症+ 提交于 2019-12-01 03:44:01

问题


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:


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.



来源:https://stackoverflow.com/questions/32160662/upload-multiple-files-with-formdata-using-angularjs-and-asp-net-mvc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!