, , , , ,

Effortlessly Master File Uploads: Elevate Your Web Experience with Our Ingenious Real-Time Progress Bar Tutorial – MVC, Javascript, C#

Posted by

Uploading files from a web interface is a common requirement for many modern web applications. In this tutorial, we’ll walk through how to implement a file upload feature using JavaScript, C# WebAPI, and the MVC pattern. Additionally, we will enhance the user experience by displaying a popup progress bar during the file upload process.

Setting Up the Environment

First, ensure you have the following:

  • Visual Studio (2017 or later)
  • .NET Core SDK

We’ll create an ASP.NET Core Web Application with MVC and WebAPI.

Creating the WebAPI Controller

Start by setting up a WebAPI controller that handles file uploads. Here’s a simple controller setup in C#:

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.IO;
using System.Threading.Tasks;

namespace FileUploadDemo.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class FileUploadController : ControllerBase
    {
        [HttpPost("upload")]
        public async Task<IActionResult> UploadFile(IFormFile file)
        {
            if (file == null || file.Length == 0)
                return Content("File not selected");

            var path = Path.Combine(Directory.GetCurrentDirectory(), "UploadedFiles", file.FileName);

            using (var stream = new FileStream(path, FileMode.Create))
            {
                await file.CopyToAsync(stream);
            }

            return Ok(new { file.FileName, size = file.Length });
        }
    }
}

This controller provides a basic API to upload files to the server’s UploadedFiles directory.

Setting Up the MVC View for File Upload

Next, let’s set up the front end. You’ll need an HTML form to handle file selection and a script to manage the upload process and show the progress:

HTML and JavaScript

Create a view with an HTML form:

<!DOCTYPE html>
<html>
<head>
    <title>File Upload</title>
</head>
<body>
    <form id="fileUploadForm">
        <input type="file" id="fileInput" name="file" />
        <button type="button" onclick="uploadFile()">Upload</button>
    </form>

    <!-- Progress Bar Modal -->
    <div id="progressModal" style="display:none;">
        <div style="position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%);">
            <progress id="fileProgress" value="0" max="100"> 0% </progress>
        </div>
    </div>

    <script>
        function uploadFile() {
            var fileInput = document.getElementById('fileInput');
            var file = fileInput.files[0];
            var formData = new FormData();
            formData.append('file', file);

            var xhr = new XMLHttpRequest();
            xhr.open('POST', '/api/fileupload/upload', true);

            xhr.upload.onprogress = function(e) {
                if (e.lengthComputable) {
                    var percentComplete = (e.loaded / e.total) * 100;
                    document.getElementById('fileProgress').value = percentComplete;
                    document.getElementById('progressModal').style.display = 'block';
                }
            };

            xhr.onload = function() {
                if (xhr.status == 200) {
                    alert('File uploaded successfully');
                    document.getElementById('progressModal').style.display = 'none';
                } else {
                    alert('Error uploading file');
                }
            };

            xhr.send(formData);
        }
    </script>
</body>
</html>

This HTML file includes a basic file input and a button that triggers the uploadFile JavaScript function when clicked. The function handles the file upload via AJAX and updates a progress bar displayed in a simple modal.

Conclusion

This setup provides a full-stack solution for uploading files in an ASP.NET Core application, complete with a real-time progress indicator. This example can be extended with additional features such as multiple file uploads, drag-and-drop areas, or more sophisticated error handling and security measures like file type validation and size limits.

By integrating JavaScript, WebAPI, and MVC, developers can efficiently handle file uploads while providing a responsive and user-friendly interface to their web applications.