find and solve || findandsolve.com
Please wait.....

Uploading File using Ajax in Asp.Net Core

Download source code from here
Uploading File using Ajax in Asp.Net Core

In this article, I will discuss how to upload files through jQuery AJAX on the ASP.NET Core MVC Razor page using C#. File uploading is a very common feature of any web application. In this blog, we are going to learn file upload using ajax without the IFormFile interface in .NET 5. If you want to upload files using the IFromFile interface in .NET 5  Click here.

Create a New Application in visual studio 2019

  1. Open your visual studio in 2019 or less than 2019 as you wish
  2. Click on Create a New Project
  3. Select ASP.NET Core Web Application and then Next
  4. Provide a Project name and confirm or change the Location. Select Create
  5. Select the latest version of .NET Core in the drop-down (.NET Core 5.0) and then select Web Application
  6. Under Authentication, select Change and set the authentication to Individual User Accounts and then select OK


After creating new project, Next I will design a view(index.cshtml) page where you will add the following HTML upload control and JavaScript code as given below.

HTML

<div class="container">
    <div class="row">
        <div class="col-sm-12">
            <div class="card">
                <div class="card-title">
                    File upload by AJAX
                </div>
                <div class="card-body">
                    <div id="upload-image">
                        <input type="file"name="file" id="file" />
                        <button class="btn btn-primary" onclick="uploadFile()">
                            Upload Image
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

JavaScript

<script>
    function uploadFile() {
       var files = document.getElementById('file').files;// $('#file').files[0];// e.target.files;
        if (files.length > 0) {
            if (window.FormData !== undefined) {
                var data = new FormData();
                for (var x = 0; x < files.length; x++) {
                    data.append("file" + x, files[x]);
                    //data.append(base64String, base64String);
                }
                $.ajax({
                    type: "POST",
                    url: '/Home/UploadImage',
                    contentType: false,
                    processData: false,
                    data: data,
                    success: function (result) {
                        alert(result)
                    },
                    error: function (xhr, status, p3, p4) {
                        alert('Something is going to wrong please try agan!');
                    }
                });
            } else {
                alert("Upgrade your browser!");
            }
        }
    };
</script>

Add this (HTML and JavaScript) code to the index.html page.

In the given above code each file from the file field and add to a FormData object (HTML5 feature). Then $.ajax() method POSTs the FormData object to the UploadFile() action of the HomeController.

Open your HomeController.cs controller and add this code as given below.

using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System.Drawing;
using System.IO;

namespace FileUploadUsingAjaxInCore.Controllers {     public class HomeController : Controller
    {
        private readonly IWebHostEnvironment _env;
        public HomeController(IWebHostEnvironment env)
        {
            _env = env;
        }
        public IActionResult Index()
        {
            return View();
        }
        [HttpPost]
        public IActionResult UploadFile()
        {             foreach (var formFile in Request.Form.Files)
            {
                var fulPath = Path.Combine(_env.ContentRootPath, "wwwroot\\files", formFile.FileName);                 using (FileStream fs = System.IO.File.Create(fulPath))
                {                     formFile.CopyTo(fs);
                    fs.Flush();
                }
                return Json("Upload image succesfully.");
            }
            return Json("Please Try Again !!");
        }
    }
}

IWebHostEnvironment: This is Provides information about the web hosting environment an application is running in.

"wwwroot\\files" : File store path

And last, add the folder name "files" under wwwroot folder like as a given image.


Run your project.If you upload file you will seen in your controller like as given below.


Upload files in ASP.NET Core - C#

How to Add/Remove multiple images using angular/Upload image .

Import (Insert) and Export Excel file

Related information

Sundar  Neupane

Sundar Neupane

I like working on projects with a team that cares about creating beautiful and usable interfaces.

If findandsolve.com felt valuable to you, feel free to share it.

Comments



Report Response