【问题标题】:Upload multiple files with FormData using AngularJS and Asp.Net MVC使用 AngularJS 和 Asp.Net MVC 使用 FormData 上传多个文件
【发布时间】:2015-11-16 14:23:04
【问题描述】:

我想使用 Angular js 上传多个文件,为此我使用 FormData() 。

这是我的表单字段

    <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" />

这是我的 Asp.Net MVC 控制器

public ActionResult AddUser(string user, HttpPostedFileBase[] files)
{
    // parse user into User
}

和角度控制器

.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) {   });
    };
});

问题是我想上传不止一张图片,一张用于 profile ,另一张用于 avatar 。当我同时上传两个时,只显示第二个覆盖前一个。我试图推送 $scope.files.push(files) 但它给出了 null。需要帮助我在那里缺少的东西。

【问题讨论】:

  • 为什么你在输入字段中有 name="file" 删除它

标签: asp.net asp.net-mvc angularjs asp.net-mvc-4 input-type-file


【解决方案1】:

更改LoadFileData 函数

$scope.LoadFileData = function (files) {
        $scope.files.push(files[0]);
    };

files 返回一个 Filelist 对象,实际的文件对象在索引 0 处。

【讨论】:

  • 兄弟如何识别个人资料和头像的图像,这给出了两个图像的数组?
  • 发送formData时使用两个不同的名称代替files数组
  • 这不起作用 avatarImage: $scope.files[0],profileImage:$scope.files[1]
  • 发送formData时如何使用两个不同的名字?
  • 我即将更新我的答案,您只需处理它,创建一个包含 id,name,profileImage,AvatarImage 的视图模型。
猜你喜欢
  • 2017-06-04
  • 1970-01-01
  • 1970-01-01
  • 2023-04-03
  • 2012-10-10
  • 1970-01-01
相关资源
最近更新 更多