【问题标题】:Recognize input type file from Request.Files in Asp.net MVC using Angular JS使用 Angular JS 在 Asp.net MVC 中识别来自 Request.Files 的输入类型文件
【发布时间】:2015-08-23 03:37:23
【问题描述】:

我的视图页面中有两个输入类型的文件控件。一个用于头像,另一个用于个人资料图像。我在后面的代码中得到了这两个图像。 这是我的 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)
        {}

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

【问题讨论】:

  • 您的输入元素应该有唯一的 id,就像任何其他元素一样。

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


【解决方案1】:

您的输入类型文件控件的名称属性都应设置为“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 代码。

【讨论】:

  • 您是否还在输入中添加了名称属性?
  • 是的,我已经补充了,http post中的转换请求和数据一定有问题。
  • 请在重试之前修复相同的 ID。
  • 我在 Request.File 中得到两张图片,但参数中为空
  • 是的,检查了也改变了ID
【解决方案2】:

您可以调整控制器操作以接受 IEnumerableHttpPostedFileBase 实例:

public ActionResult Index(IEnumerable<HttpPostedFileBase> files)

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

public ActionResult Create(HttpPostedFileBase avatar, 
                           HttpPostedFileBase profile)

More info

【讨论】:

  • 假设如果用户只输入一张图片,我怎么知道将其放在头像或个人资料中?
猜你喜欢
  • 2010-11-25
  • 2016-01-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-14
  • 2019-09-09
  • 2020-03-31
相关资源
最近更新 更多