Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/291.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 将文件作为列表发送到WebApi中的方法时出现问题_Javascript_C#_List_File_Webapi - Fatal编程技术网

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

Javascript 将文件作为列表发送到WebApi中的方法时出现问题,javascript,c#,list,file,webapi,Javascript,C#,List,File,Webapi,我有这样一个输入标签: <input type="file" name="file" accept="image/png, image/jpeg" class="choose"> <button id="bAddImage" type="button"> AddImage </button> 我这里的问题是这个列表中的文件。调用该方法后,这

我有这样一个输入标签:

<input type="file" name="file" accept="image/png, image/jpeg" class="choose">
<button id="bAddImage" type="button"> AddImage </button>
我这里的问题是这个列表中的文件。调用该方法后,这些文件将不会发送到服务器

C类#

console.log中的
formData

{“ProductNameEn”:“测试”,“产品图像”:[“{}]}

发送
ProductImages为null
,而
images
具有值

console.log中的图像

(1) [……] ​ 0:文件{name:“test.png”,lastModified:1599110560934,大小:98288,…} ​ 长度:1 ​ :数组[] 剧本:1:151

C#中的方法

[HttpPost]
公共操作结果AdminApiadProduct(AddProductRequest请求)
{
var nameEn=request.ProductNameEn;//测试
如果((request.ProductImages??new List()).Count>0)
{
**//问题是空的**
}
}

我的整个问题是,用户选择的文件没有发送到服务器,值为
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;
        }
    }

列表ProductImages
再次发送为空,您看到发送的数据了吗?您的web API版本是什么?未工作,仍然不重视该文件。
$('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 () {
                    }
                });
            });
[HttpPost]
    public ActionResult AdminApiAddProduct(AddProductRequest request)
    {
        var nameEn = request.ProductNameEn; //test

        if ((request.ProductImages ?? new List<HttpPostedFileBase>()).Count > 0)
        {
             **//Problem is NULL**
        }
    }
$(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);
            }
        });
});
[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;
        }
    }