How to Display Images in ASP.NET Core MVC

How to Display Images in ASP.NET Core MVC

In this article, I will discuss How to Display Images in ASP.NET Core MVC Application with Examples from both Databases and File Systems. Please read our previous article discussing How to Save the Uploaded file to a Database in an ASP.NET Core MVC Application with Examples. Let’s continue with the application we worked on in previous articles.

How do you display all images stored in the database to a view in ASP.NET Core MVC?

Displaying all images stored in a database to a view in an ASP.NET Core MVC application involves a few key steps:

  • Retrieve Image Data from the Database: First, we need to fetch the image data from our database in our controller.
  • Create an Action Method to Serve Each Image: We need an action method in our controller that takes an identifier (like an ID or filename) and returns the image. It is also possible to return all the image data from the database.
  • Display the Images in Your View: Finally, we need to loop through the collection of images in our view and use <img> tags to display them, referencing our action method as the source for each image.
Retrieve Images in the Controller

Please add the following action method within the FileUpload controller. The following method will return all uploaded file details from the database.

public async Task<IActionResult> ShowImages()
{
    EFCoreDbContext _context = new EFCoreDbContext();
    // Assuming 'Files' is your DbSet of images
    var images = await _context.Files.ToListAsync();
    return View(images);
}
Create an Action Method to Serve Images

You need an action method that returns the image file. This method is similar to the one you’d use for serving individual files, So, add the following action method within the FileUpload controller.

public async Task<IActionResult> GetImage(int id)
{
    EFCoreDbContext _context = new EFCoreDbContext();
    var image = await _context.Files.FirstOrDefaultAsync(f => f.Id == id);

    if (image == null)
    {
        return NotFound();
    }

    // Assuming ContentType is stored in your model
    return File(image.Data, image.ContentType);
}
Display Images in the View

In your Razor view, loop through the collection of images and use a <img> tag to display each one. So, add a view named ShowImages.cshtml within the Views/FileUpload folder and then copy and paste the following code.

@model IEnumerable<FileModel>
@{
    ViewData["Title"] = "ShowImages";
}

<h1>Uploaded Images</h1>

<div class="row">
    <div class="col-md-4">
        @foreach (var image in Model)
        {
            <img src="@Url.Action("GetImage", new { id = image.Id })" width="200" height="200" alt="Image Not Availanle" class="img-fluid" />
        }
    </div>
</div>

In this code, Model represents a collection of FileModel objects (or whatever your model is named). The foreach loop goes through each image, and the src attribute of the <img> tag points to the GetImage action method with the image’s ID.

Now, upload a few images to the database, and once you store the images, you can verify the same in the database as follows:

How to Display Images in ASP.NET Core MVC

Now, access the ShowImages action method, and you should see all the uploaded images.

Additional Considerations
  • Performance: Be aware of the performance implications of loading many large images from the database. Consider implementing pagination or lazy loading.
  • Security: Make sure that only authorized users can access private or sensitive images.
  • Caching: Implement caching to improve performance, especially for frequently accessed images.
  • Error Handling: Add error handling for cases where the image is not found or the database is unavailable.
How do you Display all Images stored in a Folder to a view in ASP.NET Core MVC?

Displaying all images stored in a folder in an ASP.NET Core MVC application requires a few steps. You’ll need to read the files from the folder, pass their paths to the view, and then render them. Here’s a step-by-step guide on how to do this:

Store Images in a Folder Accessible to Your Application

The images should be stored in a folder that’s accessible by your application. Typically, this would be a subfolder within the wwwroot directory, which is the root directory for static files in ASP.NET Core. In our example, we store all the images in the wwwroot/uploads/ folder, as shown in the image below.

How do you Display all Images stored in a Folder to a view in ASP.NET Core MVC?

Read Image File Names in the Controller

In your controller action, read the file names from the folder and pass them to the view. So, add the following action method to the FileUpload controller.

public IActionResult ShowImagesFromFolder()
{
    //Get the Folder Path
    var imageFolder = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/uploads");

    //Get the File Path
    var imageFileNames = Directory.EnumerateFiles(imageFolder)
                                  .Select(fn => Path.GetFileName(fn));
    //Return all the Images to the View
    return View(imageFileNames);
}
Create a View to Display the Images

In your Razor view, loop through the list of image file names and create a <img> tag for each one. So, add a view named ShowImagesFromFolder.cshtml within the Views/FileUpload folder and then copy and paste the following code.

@model IEnumerable<string>

@{
    ViewData["Title"] = "ShowImagesFromFolder";
}

<h1>Show Images From Folder</h1>

<div class="row">
    <div class="col-md-4">
        @foreach (var fileName in Model)
        {
            <img src="@Url.Content("~/uploads/" + fileName)" width="200" height="200" alt="Image Not Availanle" class="img-fluid" />
        }
    </div>
</div>
Configure Static Files Middleware (if not already configured)

Ensure that your application is set up to serve static files. This is typically configured in the Program.cs class file:

app.UseStaticFiles();

Now, run the application and access the ShowImagesFromFolder action method, and you should see the images.

Displaying Image from Database vs File System in ASP.NET Core MVC

Displaying images in an ASP.NET Core MVC application can be done either by retrieving them from a database or serving them from the file system. Each approach has its own considerations and best use cases.

Displaying Images from a Database

When images are stored in a database, typically as binary data (e.g., in a VARBINARY column in SQL Server), you need to retrieve the image data and then serve it to the client, often through a controller action.

  • Data Retrieval: The database stores Images as binary data (BLOBs). Retrieving an image involves querying the database, which can be slower than direct file system access, especially for large images.
  • Data Transmission: The binary data of the image needs to be read from the database and then sent to the client, typically by converting it into a suitable format like base64. This adds overhead in terms of processing and data size.
  • Scalability: Databases can become a bottleneck when scaling, especially if large amounts of binary data are frequently accessed.
  • Security: Databases often provide better security features, allowing for more controlled access to the images.
  • Backup and Recovery: Images and other data in the database are backed up, providing a consistent backup and recovery process.
  • Consistency: Maintaining transactional consistency between the image and its metadata or related data is easier.
Pros:
  • Centralized storage: All data, including images, are stored in one place, which can simplify backup and management.
  • Security: It can offer better control over who accesses the images, as you can implement more complex access logic in your application.
Cons:
  • Performance: Retrieving images from a database can be slower and more resource-intensive than serving them from a file system.
  • Complexity: It requires more code to retrieve and serve images from a database.
Displaying Images from the File System

Images stored in the file system can be served directly to the client, similar to how static files (like CSS or JavaScript files) are served.

  • Data Retrieval: Images are stored as files in the server’s file system. Retrieval is typically faster as it involves direct file system access.
  • Data Transmission: The image can be served directly to the client without converting, which can be more efficient, especially for static content.
  • Scalability: Serving static files (like images) from the file system can be highly efficient and scales well, especially when combined with caching mechanisms.
  • Security: Requires careful management of file access permissions. Direct access to files can be a security risk if not properly managed.
  • Backup and Recovery: A separate file backup process is required, independent of the database backup.
  • Independence from Database Load: Reduces the load on the database, as image requests are handled independently.
Pros:
  • Performance: Serving images from the file system is typically faster and more efficient.
  • Simplicity: It’s generally simpler to serve images directly from the file system.
Cons:
  • Security: If not handled properly, there could be security risks, such as exposing private images.
  • Management: File system storage requires careful management to handle large numbers of files, backups, etc.
Conclusion

Use database storage for images if you need tighter security and control, and the images are not accessed very frequently, or if they are relatively small in size. Use file system storage for images if performance is a key concern, especially for websites with high traffic or for larger images.

In the next article, I will discuss How to Delete Images in ASP.NET Core MVC Application with Examples. In this article, I try to explain How to Display Images in ASP.NET Core MVC Application with Examples. And I hope you enjoy this How to Display Images in ASP.NET Core MVC article.

Leave a Reply

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