将IFormFile更改为IList< IFormFile>并发送了$ http.post请求.AngularJS,ASP.NET Core [英] To change IFormFile to IList<IFormFile> and sent $http.post request. AngularJS, ASP.NET Core

查看:58
本文介绍了将IFormFile更改为IList< IFormFile>并发送了$ http.post请求.AngularJS,ASP.NET Core的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的示例仅适用于一个文件.我需要一个文件数组.我使用angularJS 1.7和asp.net-core 2.0

My example works only with one file. I need an array of files. I use angularJS 1.7 and asp.net-core 2.0

HTML

 <div class="post">
    <form>
        <textarea ng-model="Headline" name="Headline" rows="2" cols="63" class="form-control"></textarea>

        <textarea ng-model="BodyText" name="BodyText" rows="4" cols="63" class="form-control"></textarea>

        <input type = "file" file-model = "myFile" multiple/>

        <input id="Submit" class="btn btn-default" ng-click="createPost()" type="submit" value="Пост" />
    </form>
</div>

AgularJs控制器中的creatPost方法

Method creatPost in AgularJs controller

 $scope.createPost = function () {
        var model = {
            Headline: $scope.Headline,
            BodyText: $scope.BodyText,
            ImgPost: $scope.myFile
        }
        $http({
                method: 'POST',
                url: '/api/Blog/create-post/',
                headers: {
                    'Content-Type': undefined
                },
                data: model,
                transformRequest: function (data, headersGetter) {
                    var formData = new FormData();
                    angular.forEach(data, function (value, key) {
                        formData.append(key, value);
                    });

                    return formData;
                }
            })
            .then(function onSuccess(response) {
                if (response.data = "Ok") {
                    $window.location.reload();
                }
            })


            .catch(function onError(response) {
                console.log("Error")
            });
    }

C#中的模型

[ScaffoldColumn(false)]
    public int Id { get; set; }

    [ScaffoldColumn(false)]
    public string User { get; set; }

    [Required(ErrorMessage = "")]
    [StringLength(100, MinimumLength = 1, ErrorMessage = "")]
    public string Headline { get; set; }

    [Required(ErrorMessage = "")]
    [StringLength(1000, MinimumLength = 1, ErrorMessage = "")]
    public string BodyText { get; set; }

    [ScaffoldColumn(false)]
    public DateTime? Date_Time { get; set; }

    public IFormFile ImgPost { get; set; }

和方法签名

    [HttpPost]
    [Route("create-post")]
    public async Task<object> PostSaveOnFile(PostViewModel model)
    {

我需要如何在#public IFormFile ImgPost {get;放;}并在我的angularJS控制器上进行更改,我应该能够发送文件数组.谢谢.

How I need to change my model in # public IFormFile ImgPost { get; set; } And make changes on my angularJS controller and I shoud be able to sent an array of files. Thanks.

据我所知,我在fileReader的伪造中遇到的问题

As I understood the problem in my derective of fileReader

(function (angular) {
    angular.module('app').directive('fileModel', ['$parse', function ($parse) {
      return {
         restrict: 'A',
         link: function(scope, element, attrs) {
            var model = $parse(attrs.fileModel);
            var modelSetter = model.assign;

            element.bind('change', function() {
               scope.$apply(function() {
                  modelSetter(scope, element[0].files[0]);
               });
            });
         }
      };
   }]);
})(window.angular);

如果我将C#模型更改为IList或IEnumerable,它将只是第一个文件.我既不也不知道如何将我的矫正视力更改为数组

If I will change in my C# model to IList or IEnumerable it will be only the first file. I did nor understand how to change my derective to array

推荐答案

首先,您需要更新 fileModel 指令以设置文件数组而不是单个文件.您可以使用此答案,但结果数组将具有 FileList 类型,建议您进行转换更改为 Array ,因为结合其他代码更改将更加灵活

At first you need to update fileModel directive to set an array of files instead of single file. You can use this answer but the resulting array will have FileList type and I suggest you to convert it to Array because it will be more flexible in conjunction with other changes in code

app.directive('fileModel', ['$parse', function ($parse) {
  return {
     restrict: 'A',
     link: function(scope, element, attrs) {
        var model = $parse(attrs.fileModel);
        var modelSetter = model.assign;

        element.bind('change', function() {
           scope.$apply(function() {
              modelSetter(scope, Array.from(element[0].files));
           });
        });
     }
  };
}]);

为了使ASP.NET Core正确绑定 Array (或 List ),您需要将具有相同键的所有数组值添加到 FormData .例如,如果您有

In order to let ASP.NET Core properly bind an Array (or List) you need to add all array values with the same key to FormData. For instance, if you have

public List<string> Strings { get; set; }

您将需要使用 Strings

formData.append("Strings", "value1");
formData.append("Strings", "value2");
formData.append("Strings", "value3");

因此,您需要更新 transformRequest 函数,以将文件数组正确添加到 FormData

So you need to update transformRequest function to properly add an array of files to FormData

function (data, headersGetter) {
    var formData = new FormData();
    angular.forEach(data, function (value, key) {
        //you could check if value is FileList
        //but your model can hold array of primitive values like ["val1", "val2", "val3"]
        //this single check for Array covers all cases
        //and you don't need to have different check for FileList
        if (value instanceof Array) {
            for (var i = 0; i < value.length; i++) {
                formData.append(key, value[i]);
            }
            return;
        }

        formData.append(key, value);
    });

    return formData;
}

这篇关于将IFormFile更改为IList&lt; IFormFile&gt;并发送了$ http.post请求.AngularJS,ASP.NET Core的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆