How to Save Uploaded file to Database in ASP.NET Core MVC

SPONSOR AD

How to Save the Uploaded File to Database in ASP.NET Core MVC

In this article, I will discuss How to Save the Uploaded file to a Database in an ASP.NET Core MVC Application with Examples. Please read our previous article discussing restricting uploaded file Types in the ASP.NET Core MVC application with examples. Let’s continue with the application we worked on in previous articles.

How to Save the Uploaded File to Database in ASP.NET Core MVC

Now, we will see how to save the uploaded file to a database with an example. To keep things simple, we will use SQL Server database and Entity Framework Core for performing database operations in this example.

Saving an uploaded file to a database in ASP.NET Core MVC involves several steps. You need to generate a unique name for the file, save the file content to the database, and ensure that you handle the file data correctly.

Create a Model for the File

Define a model that represents the file in the database. For example, you might have a FileModel class. So, create a class file named FileModel.cs within the Models folder and then copy and paste the following code.

SPONSOR AD
namespace FileUploadInMVC.Models
{
    public class FileModel
    {
        public int Id { get; set; }
        public string FileName { get; set; }
        public byte[] Data { get; set; }
        public long Length { get; set; }
        public string ContentType { get; set; }
        // Other properties as per your requirements
    }
}
Set Up the Database Context

First, install the required packages (Microsoft.EntityFrameworkCore.SqlServer and Microsoft.EntityFrameworkCore.Tools) for Entity Framework Core, which is compatible with your .NET version.

Once you install the required Entity Framework Core packages, add the DbContext class. Create a class file named EFCoreDbContext.cs within the Models folder, and then copy and paste the following code. Ensure that your database context includes a DbSet for your file model.

using Microsoft.EntityFrameworkCore;

namespace FileUploadInMVC.Models
{
    public class EFCoreDbContext : DbContext
    {
        public EFCoreDbContext() : base()
        {
        }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            //Configuring the Connection String
            optionsBuilder.UseSqlServer(@"Server=LAPTOP-6P5NK25R\SQLSERVER2022DEV;Database=FileHandlingDB;Trusted_Connection=True;TrustServerCertificate=True;");
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
        }

        //Adding Domain Classes as DbSet Properties
        public DbSet<FileModel> Files { get; set; }
    }
}
Generating the Database:

Open Package Manager Console and Execute the following add-migration and update-database commands. You can give any name to your migration. Here, I am giving Mig1. The name that you are giving it should not be given earlier.

How to Save the Uploaded File to Database in ASP.NET Core MVC

Now, the database should be created with the following structure:

How to Save the Uploaded File to Database in ASP.NET Core MVC

Modifying the FileUpload Controller:

Next, modify the FileUpload Controller as follows

SPONSOR AD
using FileUploadInMVC.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.IO;
using System.Linq;

namespace FileUploadInMVC.Controllers
{
    public class FileUploadController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }

        [HttpPost]
        [RequestSizeLimit(10000000)] // Limit to 10 MB
        public async Task<IActionResult> SingleFileUpload(IFormFile SingleFile)
        {
            if (SingleFile == null || SingleFile.Length == 0)
            {
                ModelState.AddModelError("", "File not selected");
                return View("Index");
            }

            var permittedExtensions = new[] { ".jpg", ".png", ".gif" };
            var extension = Path.GetExtension(SingleFile.FileName).ToLowerInvariant();

            if (string.IsNullOrEmpty(extension) || !permittedExtensions.Contains(extension))
            {
                ModelState.AddModelError("", "Invalid file type.");
            }

            // Optional: Validate MIME type as well
            var mimeType = SingleFile.ContentType;
            var permittedMimeTypes = new[] { "image/jpeg", "image/png", "image/gif" };
            if (!permittedMimeTypes.Contains(mimeType))
            {
                ModelState.AddModelError("", "Invalid MIME type.");
            }

            if (ModelState.IsValid)
            {
                //Creating a unique File Name
                var uniqueFileName = Guid.NewGuid().ToString() + Path.GetExtension(SingleFile.FileName);

                var filePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/uploads", uniqueFileName);

                //Using Buffering
                //using (var stream = System.IO.File.Create(filePath))
                //{
                //    // The file is saved in a buffer before being processed
                //    await SingleFile.CopyToAsync(stream);
                //}

                //Using Streaming
                using (var stream = new FileStream(filePath, FileMode.Create, FileAccess.Write))
                {
                    //This will save to Local folder
                    await SingleFile.CopyToAsync(stream);
                }

                // Create an instance of FileModel
                var fileModel = new FileModel
                {
                    FileName = uniqueFileName,
                    Length = SingleFile.Length,
                    ContentType = mimeType,
                    Data = ConvertToByteArray(filePath)
                };

                // Save to database
                EFCoreDbContext _context = new EFCoreDbContext();
                _context.Files.Add(fileModel);
                await _context.SaveChangesAsync();

                // Process the file here (e.g., save to the database, storage, etc.)
                return View("UploadSuccess");
            }

            return View("Index");
        }

        //This method will convert the uploaded file into byte array
        private byte[] ConvertToByteArray(string filePath)
        {
            byte[] fileData;

            //Create a File Stream Object to read the data
            using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
            {
                using (BinaryReader reader = new BinaryReader(fs))
                {
                    fileData = reader.ReadBytes((int)fs.Length);
                }
            }

            return fileData;
        }
    }
}

Now, run the application and upload a file. It should be stored in the database, as shown in the image below.

Save the Uploaded file to a Database in an ASP.NET Core MVC Application with Examples

When should you save the uploaded file to the database in an ASP.NET Core MVC?

Saving uploaded files to a database in an ASP.NET Core MVC application is a decision that depends on several factors. Here are some scenarios where storing files in a database might be appropriate, along with considerations for when to choose this approach:

  • Small Files and Documents: If the uploaded files are small and not accessed frequently (e.g., user profile pictures, small PDF documents), storing them in a database can be convenient for backup and restore processes.
  • Security and Access Control: For applications where security and fine-grained access control are paramount (e.g., confidential documents), databases can offer more sophisticated security features than file systems.
  • Transactional Integrity: When you need to maintain transactional integrity between the file and other data, such as in a banking system where each transaction record might be linked to a scanned document.
  • Data Portability: If the application is distributed or needs high data portability, storing files in the database can simplify data transfer between different servers or environments.
  • Simplified Backup and Recovery: When backups and disaster recovery processes are centralized, storing files in the database can simplify these processes by keeping everything in one place.
Considerations for Storing Files in a Database:
  • Performance: Databases are generally slower at serving files than file systems, especially for large files or high-volume access scenarios.
  • Scalability: Databases can become less efficient if they contain large amounts of binary data, impacting overall application performance.
  • Cost: Larger databases can incur higher storage and management costs than file systems, especially in cloud-hosted environments.
  • Complexity: Retrieving and serving files from a database can be more complex than using a file system.
When should you save the uploaded file to the file system in an ASP.NET Core MVC?

Saving uploaded files to the file system in an ASP.NET Core MVC application is often the preferred choice for several reasons. Here are scenarios and justifications for when you might choose to store files on the file system:

  • Large Files or Media Content: For handling large files such as videos, images, or large documents, file systems are typically more efficient and faster than databases.
  • High-Volume File Access: If your application requires frequent access to uploaded files, file systems offer better performance with lower overhead than databases.
  • Simplifying Backup and Restore: Separating file storage from the database can simplify backup and restore processes, especially for large data sets.
  • Scalability: File systems are generally easier to scale out, especially when using cloud storage solutions or distributed file systems.
  • Cost-Effectiveness: Storing large amounts of data in a database can be more expensive than using file systems, particularly in cloud-hosted environments where storage costs are a consideration.
  • Reducing Database Load: Keeping files out of the database helps reduce its size and load, improving database performance and management.
  • Content Delivery: For content-driven applications (e.g., media sites, document libraries), file systems can be integrated with Content Delivery Networks (CDNs) for efficient content delivery.
Considerations for Storing Files in the File System:
  • Security: Implement proper security measures to protect files stored on the file system, especially if sensitive data is involved.
  • File Management: Develop a strategy for organizing, naming, and managing files to avoid conflicts and ensure efficient access.
  • Backup and Disaster Recovery: Ensure that processes are in place for backing up and recovering files stored on the file system.
  • Access Control: If your application requires complex file access control logic, you must implement this at the application level.

In the next article, I will discuss How to Display Images in ASP.NET Core MVC Application with Examples. In this article, I try to explain How to Save the Uploaded file to a Database in an ASP.NET Core MVC Application with Examples. I hope you enjoy this How to Save the Uploaded File to Database in ASP.NET Core MVC article.

SPONSOR AD

Leave a Reply

Your email address will not be published. Required fields are marked *