Upload Form data and File in ASP.Net Core using jQuery Ajax

SajidHussa
 
on Jan 03, 2022 12:47 AM
1555 Views

I have two fileuploads one for aadhar and the second for pan and some data also like name email address, aadhar no, pan  no etc.

i am using asp.net core 5.0.

how to upload file and data also using ajax.

Download FREE API for Word, Excel and PDF in ASP.Net: Download
dharmendr
 
on Jan 03, 2022 01:08 AM
on Jan 03, 2022 05:13 AM

Hi SajidHussa,

Use HTML5 FormData to pass the value to the Controller using jQuery Ajax.

Check this example. Now please take its reference and correct your code.

Namespaces

using System.IO;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Hosting;

Controller

public class HomeController : Controller
{
    private IHostingEnvironment Environment;

    public HomeController(IHostingEnvironment _environment)
    {
        Environment = _environment;
    }

    public IActionResult Index()
    {
        return View();
    }

    [HttpPost]
    public JsonResult Index(string firstName, string lastName, IFormFile postedFile1, IFormFile postedFile2)
    {
        string wwwPath = this.Environment.WebRootPath;
        string contentPath = this.Environment.ContentRootPath;

        string pathPhoto = Path.Combine(this.Environment.WebRootPath, "Photos");
        if (!Directory.Exists(pathPhoto))
        {
            Directory.CreateDirectory(pathPhoto);
        }
        string photoName = Path.GetFileName(postedFile1.FileName);
        using (FileStream stream = new FileStream(Path.Combine(pathPhoto, photoName), FileMode.Create))
        {
            postedFile1.CopyTo(stream);
        }

        string pathDocument = Path.Combine(this.Environment.WebRootPath, "Documents");
        if (!Directory.Exists(pathDocument))
        {
            Directory.CreateDirectory(pathDocument);
        }
        string docName = Path.GetFileName(postedFile2.FileName);
        using (FileStream stream = new FileStream(Path.Combine(pathDocument, docName), FileMode.Create))
        {
            postedFile2.CopyTo(stream);
        }

        string message = string.Format("Name: <b>{0} {1}</b><br />Photo: <b>{2}</b><br />Document: <b>{3}</b>", firstName, lastName, photoName, docName);
        return Json(new { Status = "success", Message = message });
    }
}

View

@addTagHelper*, Microsoft.AspNetCore.Mvc.TagHelpers
@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
    <style type="text/css">
        body {
            font-family: Arial;
            font-size: 10pt;
        }

        table {
            border: 1px solid #ccc;
        }

            table th {
                background-color: #F7F7F7;
                color: #333;
                font-weight: bold;
            }

            table th, table td {
                padding: 5px;
                border-color: #ccc;
            }
    </style>
</head>
<body>
    <form id="myForm" method="post" enctype="multipart/form-data" asp-controller="Home" asp-action="Index">
        <table>
            <tr>
                <td>First Name: </td>
                <td><input type="text" id="txtFirstName" /></td>
            </tr>
            <tr>
                <td>Last Name: </td>
                <td><input type="text" id="txtLastName" /></td>
            </tr>
            <tr>
                <td>Photo: </td>
                <td><input id="fuPhoto" type="file" name="postedFile1" /></td>
            </tr>
            <tr>
                <td>Document: </td>
                <td><input id="fuDocument" type="file" name="postedFile2" /></td>
            </tr>
            <tr>
                <td></td>
                <td><input type="button" value="Submit" onclick="AjaxFormSubmit()" /></td>
            </tr>
        </table>
        <hr />
        <span id="lblMessage"></span>
    </form>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script type="text/javascript">
        function AjaxFormSubmit() {
            //Set the URL.
            var url = $("#myForm").attr("action");
            //Add the Field values to FormData object.
            var formData = new FormData();
            formData.append("firstName", $("#txtFirstName").val());
            formData.append("lastName", $("#txtLastName").val());
            formData.append("postedFile1", $("#fuPhoto")[0].files[0]);
            formData.append("postedFile2", $("#fuDocument")[0].files[0]);

            $.ajax({
                type: 'POST',
                url: url,
                data: formData,
                processData: false,
                contentType: false
            }).done(function (response) {
                if (response.Status === "success") {
                    $("#lblMessage").html(response.Message);
                }
            });
        }
    </script>
</body>
</html>

Screenshot