使用 Angular JS 在 Asp.net MVC 中识别来自 Request.Files 的输入类型文件

Recognize input type file from Request.Files in Asp.net MVC using Angular JS

我的视图页面中有两个输入类型文件控件。一个用于头像,另一个用于个人资料图像。而且我在代码后面得到了两个图像。 这是我的 AngularJS 控制器

    var app = angular.module('ProfileModule', []);
app.controller('ProfileController',['$scope','$http', function ($scope,$http) {
    $scope.user = {};
    $scope.files = [];
    var formData = new FormData();
    $scope.LoadFileData = function (files) {
        for (var file in files) {
            formData.append("file", files[file]);
        }
    };
    $scope.submit = function () {
        $http({
            url: "/Profiles/Edit",
            method: "POST",
            headers: { "Content-Type": undefined },
            transformRequest: function (data) {
                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 }
        })
        .success(function (response) { });
    }
}]);

这是两个控件

<input id="selector" type="file"   onchange="angular.element(this).scope().LoadFileData(this.files)" accept="image/*">



<input id="selector" type="file"   onchange="angular.element(this).scope().LoadFileData(this.files)" accept="image/*">

这是我的 MVC 控制器

public ActionResult Edit(string user, HttpPostedFileBase[] files)
        {}

我在字符串中获取剩余模型值,稍后将其解析为模型,但图像文件在文件中显示为空,因此我在 Request.Files 中获取它们。 我应该做什么编辑才能在数组中获取该图像文件。

您只需调整您的控制器操作即可接受 IEnumerableHttpPostedFileBase 个实例:

public ActionResult Index(IEnumerable<HttpPostedFileBase> files)

如果您想上传多个文件字段,每个文件字段都具有不同的名称,为了让模型绑定器正确绑定它们,您的控制器操作签名应如下所示:

public ActionResult Create(HttpPostedFileBase avatar, 
                           HttpPostedFileBase profile)

More info

您的两个输入类型文件控件都应将名称属性设置为类似 "profileImage" 和 "avatarImage" 的内容。然后像这样定义你的控制器动作:

[HttpPost]
ActionResult Edit (string user, HttpPostedFileBase profileImage, HttpPostedFileBase avatarImage)
{
...
}

和html:

<input id="selector" name="profileImage" type="file" onchange="angular.element(this).scope().LoadFileData(this.files)" accept="image/*"> 

<input id="selector" name="avatarImage" type="file" onchange="angular.element(this).scope().LoadFileData(this.files)" accept="image/*">

编辑:检查参数是否为非空,然后就可以开始了。

编辑:将用户参数添加到控制器操作。

编辑:添加了 html 代码。