[Solved] HttpPostedFile always returns NULL send with FormData using jQuery AJAX in ASP.Net MVC

ahmad22yusoff
 
on Sep 10, 2021 10:50 PM
Sample_696314.zip
692 Views

Hi 

I have some problem with image upload function posting formData to server side action method as "Controller", because ajax call "imgFile" doesn't send files to server side.

It's works but posted formData "imgFile" in server side is always null.

Please help me to check my coding on below:

In view:  

<div class="form-group">
    @Html.Label("Image", htmlAttributes: new { @class = "control-label col-md-2" })<span id="lblProgessMessage" style="color: Green"></span>
    <div class="col-md-10">
        <input type="file" name="imgFile" id="imgFile" onchange="imgUploadChange(event)" accept="image/png, image/jpeg, image/gif, image/jpg" /><br/>
        <img id="myUploadedImg" style="width:180px; height:150px;"/>
        <br /><progress id="fileProgress" style="display: none"></progress>
    </div>
<div class="form-group">
    <div class="col-md-offset-2 col-md-10">
        <input type="submit" value="Create" id="btnCreate" class="btn btn-warning" />
        @Html.ActionLink("Cancel", "Index1", null, new { @class = "btn btn-warning" })
    </div>
</div>

In javascript:

$('#btnCreate').on('click', function (e) {
    //Add the Field values to FormData object.
    var formData = new FormData();
    //var imagefile = document.getElementById("imgFile").files[0];
    //formData.append("imgFile", imagefile);
    formData.append("imgFile", $("#imgFile")[0].files[0]);
    formData.append("JPAPER_QUES_TEXT", $("#JPAPER_QUES_TEXT").val());
     $.ajax({
        url: '@Url.Action("Create", "QuestionsPaper")',
        contentType: false,
        processData: false,
        type: "POST",
        dataType: 'json',
        contentType:"multipart/form-data",
        data: formData,
        success: function (response) {
            alert('save successfully.');
            $("#fileProgress").hide();
            $("#lblProgressMessage").html("<b>" + response + "</b> has been uploaded.");},
        xhr: function () {
            var fileXhr = $.ajaxSettings.xhr();
            if (fileXhr.upload) {
                $("progress").show();
                fileXhr.upload.addEventListener("progress", function (e) {
                    if (e.lengthComputable) {
                        $("#fileProgress").attr({
                            value: e.loaded,
                            max: e.total
                        });
                    }
                }, false);
            }
            return fileXhr;
        },
        error: function (error) {
            alert('something happen in script.');
            console.log('error:' +imgFile);
        }
  
    });
});

In Controller part:

public JsonResult Create(CombineModels.PAPER_QUES_VM model, HttpPostedFile imgFile)
{ 
    try
    {
        Thread.Sleep(50);
        List<PAPER> lPaper = db.PAPERs.Where(P => P.PAPER_STATUS == "01").ToList();
        ViewBag.TestCodeList = new SelectList(lPaper, "PAPER_ID", "PAPER_TESTCODE");
 
        //validating Model state  
        if (ModelState.IsValid)
        {
            //Getting File Details
            if (imgFile != null && imgFile.ContentLength > 0)
            {
                string imgName = Path.GetFileName(imgFile.FileName);
                string extension = Path.GetExtension(imgName);
                imgName = imgName + DateTime.Now.ToString("yyyymmssfff") + extension;
                string imgPath = Path.Combine(Server.MapPath("~/images/uploads/"), imgName);
                imgFile.SaveAs(imgPath);
 
                if (string.IsNullOrEmpty(model.JPAPER_QUES_IMAGENAME))
                {
                    model.JPAPER_QUES_IMAGENAME = "";
                    model.JPAPER_QUES_IMAGEPATH = "";
                }
                else
                {
                    model.JPAPER_QUES_IMAGENAME = imgName;
                    model.JPAPER_QUES_IMAGEPATH = imgPath;
                  }
            }
            .............
        }

Thank you in advance!

Yusoff

Download FREE API for Word, Excel and PDF in ASP.Net: Download
dharmendr
 
on Sep 11, 2021 03:44 AM
on Sep 13, 2021 06:59 AM

Hi ahmad22yusoff,

Use HttpContext.Request object to get the files.

Check below example.

Model

public class CustomerModel
{
    public string JPAPER_QUES_TEXT { get; set; }
}

Controller

public class HomeController : Controller
{
    // GET: Home
    public ActionResult Index()
    {
        return View();
    }

    public ActionResult Create(CustomerModel customer)
    {
        if (HttpContext.Request.Files.Count > 0)
        {
            HttpPostedFileBase imgFile = HttpContext.Request.Files[0];
            string imgName = Path.GetFileNameWithoutExtension(imgFile.FileName);
            string extension = Path.GetExtension(imgFile.FileName);
            imgName = imgName + DateTime.Now.ToString("yyyymmssfff") + extension;
            string imgPath = Path.Combine(Server.MapPath("~/images/uploads/"), imgName);
            imgFile.SaveAs(imgPath);
        }
        return Json("");
    }
}

View

@model FileUpload_FormData_MVC.Models.CustomerModel

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script type="text/javascript">
        $(function () {
            $('#btnCreate').on('click', function (e) {
                var formData = new FormData();
                formData.append("imgFile", $("#imgFile")[0].files[0]);
                formData.append("JPAPER_QUES_TEXT", $("#JPAPER_QUES_TEXT").val());
                $.ajax({
                    url: '@Url.Action("Create", "Home")',
                    type: "POST",
                    data: formData,
                    cache: false,
                    contentType: false,
                    processData: false,
                    success: function (response) {

                    },
                    error: function (error) {
                        alert('something happen in script.');
                        console.log('error:' + imgFile);
                    }
                });
            });
        });
    </script>
</head>
<body>
    <input type="text" name="Name" id="JPAPER_QUES_TEXT" />
    <input type="file" name="imgFile" id="imgFile" accept="image/png, image/jpeg, image/gif, image/jpg" multiple />
    <input type="submit" value="Create" id="btnCreate" class="btn btn-warning" />
</body>
</html>

Screenshot

ahmad22yusoff
 
on Sep 13, 2021 09:52 PM

Hi,

Finally i can save image to database from view which follow your reference step by step.

Main cause issue is i used wrong code for coding on this 

 @using (Html.BeginForm(new {enctype = "multipart/form-data" }))

Thank you.

Yusoff