Upload File in ASP.NET Core MVC Using AJAX in dotnet 8

Upload File in ASP.NET Core MVC Using AJAX in dotnet 8
In this article [Show more]

    Upload File in ASP.NET Core MVC Using AJAX

    Uploading files is a common requirement in modern web applications. In ASP.NET Core MVC, handling file uploads efficiently can improve the usability and performance of your applications. In this article, we'll explore how to implement file uploads in an ASP.NET Core MVC application using AJAX, which provides a smoother user experience by allowing file uploads without a full page refresh.

    Prerequisites

    To follow along with this tutorial, you should have the following:

    • .NET 8 SDK installed on your machine.
    • A basic understanding of ASP.NET Core MVC and C#.
    • Familiarity with AJAX and JavaScript.

    Setting Up the Project

    Start by creating a new ASP.NET Core MVC project. You can do this using the .NET CLI:

     

    dotnet new mvc -n AjaxFileUpload
    cd AjaxFileUpload
    

    This command creates a new project named AjaxFileUpload and sets up the basic MVC structure.

    Adding the File Upload Feature

    Step One: Update the Model

    Create a model that will represent the file input from the user. Although for a simple file upload you might not need a complex model, it's good practice to use models to pass data:

    public class FileUploadModel
    {
        public IFormFile File { get; set; }
    }
    

    Step Two: Create the View

    Add a new View under Views/Home named Index.cshtml. This view will contain the form for uploading files:

    @{
        ViewData["Title"] = "Home Page";
    }
    
    <form id="fileUploadForm" method="post" enctype="multipart/form-data">
        <input type="file" name="file" />
        <input type="button" value="Upload" onclick="uploadFile()" />
    </form>
    
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script>
    function uploadFile() {
        var formData = new FormData($('#fileUploadForm')[0]);
        $.ajax({
            url: '/Home/UploadFile',
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            success: function (response) {
                alert('File uploaded successfully!');
            },
            error: function () {
                alert('Error uploading file.');
            }
        });
    }
    </script>
    

    This form uses AJAX for submitting the file, where the uploadFile function handles the submission process without reloading the page.

    Interface Preview

    After implementing the file upload functionality in your ASP.NET Core MVC application using AJAX, you will see the interface as shown in the image below. This interface includes a "Choose File" button, allowing users to select the file they wish to upload. Once a file is selected, the file name will appear next to the button. To upload the selected file to the server, users can click the "Upload" button. This process is handled in the background by AJAX, ensuring a smooth and seamless user experience without the need for a page refresh.

     

    Step Three : Add the Controller Action

    In your HomeController, add an action to handle the file upload:

     

    using Microsoft.AspNetCore.Http;
    using Microsoft.AspNetCore.Mvc;
    using System.IO;
    using System.Threading.Tasks;
    
    public class HomeController : Controller
    {
        [HttpPost]
        public async Task<IActionResult> UploadFile(IFormFile file)
        {
            if (file != null && file.Length > 0)
            {
                var path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/uploads", file.FileName);
                
                using (var stream = new FileStream(path, FileMode.Create))
                {
                    await file.CopyToAsync(stream);
                }
    
                return Json(new { success = true, message = "File uploaded successfully" });
            }
    
            return Json(new { success = false, message = "No file uploaded" });
        }
    }
    

    This action receives the uploaded file and saves it to the wwwroot/uploads directory.

     

    Understanding the File Upload Controller Method

    The screenshot illustrates a portion of the UploadFile action method in the controller, designed to handle file uploads in an ASP.NET Core MVC application. This method accepts a parameter of type IFormFile, which is a special interface provided by ASP.NET Core to handle uploaded files.

    Key Points of the Controller Method:

    Parameter Inspection: The method first checks if the uploaded file (file) is not null and its size is greater than 0 to ensure a file has indeed been uploaded and is not empty.

    File Storage: If a valid file is present, the method computes a path to store the file using Path.Combine. This combines the current directory's path with a subdirectory and the file name, ensuring that the file is saved in the designated location (wwwroot/uploads).

    File Saving: The file is saved using a FileStream. The using statement ensures that the FileStream is properly disposed of after the file is saved, which is crucial for freeing up system resources and avoiding file lock issues.

    Response: After successfully saving the file, the method returns a JSON response indicating success. If no file is uploaded, it returns a different JSON response indicating failure.

    About IFormFile:

    • Usage: IFormFile is an interface that represents a file sent with the HttpRequest. It provides properties and methods for accessing the uploaded file's metadata and content.
    • Properties: Key properties include FileName, ContentType (the MIME type of the file), and Length (the size of the file in bytes).
    • Methods: It includes methods such as CopyToAsync, which copies the contents of the uploaded file to a target stream, allowing for asynchronous file handling.

    This method ensures that file uploads are handled efficiently and securely, with clear feedback provided to the user regarding the upload status. By integrating AJAX, the file upload process does not require a page reload, enhancing the overall user experience.

     

     

    Successful File Storage on the Server

    The screenshot above shows the uploads directory located inside the wwwroot folder of your ASP.NET Core MVC application. This directory is where files uploaded through the application are stored. As depicted, the file 2.jpg has been successfully uploaded and is now stored in the server's file system.

    Setting Up the uploads Directory:

    To ensure that your application can store uploaded files, you need to create an uploads folder inside the wwwroot directory of your ASP.NET Core project. This setup is crucial because the code in the controller constructs the file path based on this directory. Here’s how to set it up:

    Create the Directory: Navigate to the wwwroot folder of your project. Right-click and choose New > Folder, and name it uploads.

    Permissions: Ensure that your application has the necessary permissions to write to this folder. This is typically handled by your server's configuration but may require manual adjustments depending on your hosting environment.

    This directory structure and setup ensure that all files uploaded through the application are organized and stored securely within your project’s file system, accessible for any further processing or retrieval needed by the application.

     

     

     

    Conclusion

    In this tutorial, you learned how to handle file uploads in an ASP.NET Core MVC application using AJAX. This method not only improves the performance by avoiding unnecessary page reloads but also enhances the user experience by making the application feel more dynamic and responsive.

    Author Information
    • Author: Ehsan Babaei

    Send Comment



    Comments