0

I have an Input tag like this:

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

After the user clicks the bAddImage button, if the user has selected a file, this file will be saved in an Array List in jQuery as follows:

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

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

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

The problem I have here are the files in this list. These files will not be sent to the server after calling the method.

Class C#

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

Call Method in 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 in console.log

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

Sends ProductImages is null while images have a value.

images in console.log

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

Method in C#

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

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

The whole problem I have is that the files selected by the user are not sent to the server and the value is ProductImages = null.

1 Answers1

0

You must use FormData instead of JSON and append you Image one by one with other data to it, I have modified your code

$(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);
            }
        });
});

in your action get files using 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;
        }
    }
Sina Riani
  • 325
  • 4
  • 17