问题将文件作为列表发送到 WebApi 中的方法

Problem Send a file as a list to a method in WebApi

我有一个这样的输入标签:

<input type="file" name="file" accept="image/png, image/jpeg" class="choose">
<button id="bAddImage" type="button"> AddImage </button>

用户点击bAddImage按钮后,如果用户选择了一个文件,这个文件将保存在一个Array List中jQuery如下:

$('body').on('click',
            '#bAddImage',
            function(event) {
                event.preventDefault();

                if ($('.choose')[0].files[0] == null) {
                    return;
                }

                IMAGES.push({
                    File: $('.choose')[0].files[0],
                });
            });

我遇到的问题是这个列表中的文件。调用该方法后,这些文件不会发送到服务器。

Class C#

public class AddProductRequest
{
    public string ProductNameEn { get; set; }
    public List<HttpPostedFileBase> ProductImages { get; set; }
}

在JavaScript

中调用方法
$('body').on('click',
            '#bSubmit',
            function(event) {
                event.preventDefault();

                var images = [];
                if (IMAGES.length > 0) {
                    $.each(IMAGES,
                        function (index, item) {
                            images.push({
                                item.File
                            });
                        });
                }

                const formData = JSON.stringify({
                    ProductNameEn: 'test',
                    ProductImages: images  *\not send value*
                });

                $.ajax({
                    type: "POST",
                    url: '@Url.Action("AdminApiAddProduct", "CallApi", new {area = "AdminArea"})',
                    contentType: "application/json",
                    dataType: "json",
                    data: formData,
                    success: function (response) {

                    },
                    error: function () {
                    }
                });
            });

formData 在 console.log

{"ProductNameEn":"test","ProductImages":["{}"]}

发送 ProductImages is nullimages 有值。

images 在 console.log

(1) […] ​ 0: File { name: "test.png", lastModified: 1599110560934, size: 98288, … } ​ length: 1 ​ : Array [] script:1:151

C#中的方法

[HttpPost]
    public ActionResult AdminApiAddProduct(AddProductRequest request)
    {
        var nameEn = request.ProductNameEn; //test

        if ((request.ProductImages ?? new List<HttpPostedFileBase>()).Count > 0)
        {
             **//Problem is NULL**
        }
    }

我遇到的全部问题是用户选择的文件没有发送到服务器,值是ProductImages = null

你必须使用 FormData 而不是 JSON 并将你的图像与其他数据一张一张地附加到它上面,我已经修改了你的代码

$(function () {
var formData = new FormData();
$('body').on('click',
    '#bAddImage',
    function (event) {
        event.preventDefault();

        if ($('.choose')[0].files[0] == null) {
            return;
        }

        formData.append($(".choose")[0].files[0].name, $(".choose")[0].files[0]);
    });

    $("body").on("click", "#bSubmit", function (e) {
        e.preventDefault();

        $.ajax({
            url: '/api/CallApi/AdminApiAddProduct',
            type: 'POST',
            data: formData,
            cache: false,
            contentType: false,
            processData: false,
            success: function (fileName) {
                // success code
            },
             error: function (error) {
                console.log(error);
            }
        });
});

在您的操作中使用 HttpContext.Current.Request.Files

获取文件
[HttpPost]
    [Route("api/CallApi/AdminApiAddProduct")]
    public IHttpActionResult AdminApiAddProduct()
    {
        try
        {
            var httpRequest = HttpContext.Current.Request;

            if (httpRequest.Files.Count > 0)
            {
                foreach (string file in httpRequest.Files)
                {
                    var postedFile = httpRequest.Files[file];
                    var filePath = HttpContext.Current.Server.MapPath("~/" + postedFile.FileName);
                    postedFile.SaveAs(filePath);
                }
                return Ok("files uploaded!");
            }
            return Ok("no files to upload!");
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }