Upload file in ASP.NET Core MVC using jQuery Ajax


This article is going to explain how to upload a file in ASP.NET Core MVC using jQuery Ajax.

The following is a controller code. Here IWebHostEnvironment is injected via the HomeController constructor to get the root path. In the FileUpload action method the parameter IFormFile has been passed to upload the files.

Note:
To save the uploaded file, create a folder name Upload in wwwroot.
 
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using System.IO;

public class HomeController : Controller
{
    private readonly IWebHostEnvironment _env;
    public HomeController(IWebHostEnvironment hostingEnv)
    {
        _env = hostingEnv;
    }

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

    public async Task<IActionResult> FileUpload(IFormFile formFile)
    {
        try
        {
           // To get the physical path of the upload file in wwwroot
            var filePath = Path.Combine(_env.WebRootPath, "Upload", formFile.FileName);
            using var stream = new FileStream(filePath, FileMode.Create);

           // To copy the file to the target stream
            await formFile.CopyToAsync(stream);
            return Json(new { status = "success", fileName = formFile.FileName, fileSize= formFile.Length });
        }
        catch (Exception ex)
        {
            return Json(new { status = "error "+ ex.Message });
        }      
    }
}

The following is a view code. Here google jQuery CDN is added to use jQuery.

@{
    ViewData["Title"] = "File Upload";
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

<form id="fileUploadForm" method="post" enctype="multipart/form-data" asp-controller="Home" asp-action="FileUpload">
    Upload file: 
    <input type="file" id="uploadFile" name="uploadFile" />
    <input type="submit" value="Upload" />

    <div>
        <br />
        <div id="messageDiv" style="font-weight:bold; color:green"></div>
        <br />
        File Name: <strong><span id="fileNameSpan"></span></strong>
        <br />
        File Size: <strong><span id="fileSizeSpan"></span></strong>
    </div>
</form>

The following is a jQuery. This will trigger the form submission event when clicking the submit button. If the file is uploaded successfully, it will show the file name and size of the uploaded file. If not, it will display an error message.

<script>
    $(function () {
        $("#fileUploadForm").submit(function (e) {
            e.preventDefault();

            var data = new FormData();
            data.append("formFile", $("#uploadFile")[0].files[0]);

            $.ajax({
                type: 'post',
                url: "/Home/FileUpload",
                data: data,
                processData: false,
                contentType: false
            }).done(function (result) {
                if (result.status === "success") {
                    $("#messageDiv").html("File uploaded successfully");
                    $("#fileNameSpan").html(result.fileName);
                    $("#fileSizeSpan").html(result.fileSize);
                }
                else {
                    alert(result.status);
                }
            });
        });
    })
</script>

The following is an output of the above code.


I hope this will help you. Keep coding

Comments

Popular posts from this blog

Entity Framework Core (EF) with SQL Server LocalDB

Exploring EventCallback in Blazor: Building Interactive Components

A Step-by-Step Guide to Implementing Identity in ASP.NET Core MVC