How to Upload Image in Database and Display Image from Database into Gridview ImageField in Asp.Net MVC ?

How to Upload Image in Database and Display Image from Database into Gridview ImageField in Asp.Net MVC ?

Use these instructions to upload an image to a database and display it in an ASP.NET MVC GridView. This example will show how to accept picture uploads, store them in a SQL Server database, and retrieve them for display.

Step 1: Set Up Your Database

  • Create a SQL Server Database:Open SQL Server Management Studio (SSMS).
  • Create a new database named ImageUploadDB.
  • Create a Table for Images:Execute the following SQL script to create a table that will store image details:

sql

  1. CREATE TABLE Images (
  2. Id INT PRIMARY KEY IDENTITY(1,1),
  3. Name NVARCHAR(100),
  4. ContentType NVARCHAR(50),
  5. Data VARBINARY(MAX)
  6. );

Step 2: Create the ASP.NET MVC Project

  1. Open Visual Studio.
  • Create a new ASP.NET MVC project:Go to File > New > Project.
  • Select ASP.NET Web Application and name your project (e.g., ImageUploadApp).
  • Choose the MVC template and click OK.

Step 3: Create the Model

  • Create a Model Class:In the Models folder, create a new class named ImageModel.cs:

csharp

  1. public class ImageModel
  2. {
  3. public int Id { get; set; }
  4. public string Name { get; set; }
  5. public string ContentType { get; set; }
  6. public byte[] Data { get; set; }
  7. }

Step 4: Create the Controller

  • Create a Controller:Right-click on the Controllers folder and add a new controller named ImageController.cs:

csharp

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Data.SqlClient;
  4. using System.IO;
  5. using System.Web;
  6. using System.Web.Mvc;
  7. using YourNamespace.Models; // Update with your actual namespace
  8. public class ImageController : Controller
  9. {
  10. private string connectionString = “YourConnectionStringHere”; // Update with your connection string
  11. public ActionResult Index()
  12. {
  13. List<ImageModel> images = new List<ImageModel>();
  14. using (SqlConnection conn = new SqlConnection(connectionString))
  15. {
  16. conn.Open();
  17. SqlCommand cmd = new SqlCommand(“SELECT * FROM Images”, conn);
  18. SqlDataReader reader = cmd.ExecuteReader();
  19. while (reader.Read())
  20. {
  21. images.Add(new ImageModel
  22. {
  23. Id = (int)reader[“Id”],
  24. Name = reader[“Name”].ToString(),
  25. ContentType = reader[“ContentType”].ToString(),
  26. Data = (byte[])reader[“Data”]
  27. });
  28. }
  29. }
  30. return View(images);
  31. }
  32. [HttpPost]
  33. public ActionResult Upload(HttpPostedFileBase file)
  34. {
  35. if (file != null && file.ContentLength > 0)
  36. {
  37. byte[] data;
  38. using (var binaryReader = new BinaryReader(file.InputStream))
  39. {
  40. data = binaryReader.ReadBytes(file.ContentLength);
  41. }
  42. using (SqlConnection conn = new SqlConnection(connectionString))
  43. {
  44. conn.Open();
  45. SqlCommand cmd = new SqlCommand(“INSERT INTO Images (Name, ContentType, Data) VALUES (@Name, @ContentType, @Data)”, conn);
  46. cmd.Parameters.AddWithValue(“@Name”, Path.GetFileName(file.FileName));
  47. cmd.Parameters.AddWithValue(“@ContentType”, file.ContentType);
  48. cmd.Parameters.AddWithValue(“@Data”, data);
  49. cmd.ExecuteNonQuery();
  50. }
  51. }
  52. return RedirectToAction(“Index”);
  53. }
  54. }

Step 5: Create the Index View

  • Create the Index View:Right-click on the Index action in ImageController and select Add View.
  • Name the view Index.cshtml.

xml

  1. @model IEnumerable<YourNamespace.Models.ImageModel> // Update with your actual namespace
  2. @{
  3. ViewBag.Title = “Image Upload”;
  4. }
  5. <h2>Upload Image</h2>
  6. @using (Html.BeginForm(“Upload”, “Image”, FormMethod.Post, new { enctype = “multipart/form-data” }))
  7. {
  8. <div>
  9. <input type=”file” name=”file” />
  10. <input type=”submit” value=”Upload” />
  11. </div>
  12. }
  13. <h2>Uploaded Images</h2>
  14. <table class=”table”>
  15. <thead>
  16. <tr>
  17. <th>ID</th>
  18. <th>Name</th>
  19. <th>Image</th>
  20. </tr>
  21. </thead>
  22. <tbody>
  23. @foreach (var image in Model)
  24. {
  25. <tr>
  26. <td>@image.Id</td>
  27. <td>@image.Name</td>
  28. <td>
  29. <img src=”@Url.Action(“GetImage”, “Image”, new { id = image.Id })” alt=”@image.Name” style=”width:100px;height:100px;” />
  30. </td>
  31. </tr>
  32. }
  33. </tbody>
  34. </table>

Step 6: Create the GetImage Action

  1. Add a method to retrieve the image in ImageController:csharp
  2. public ActionResult GetImage(int id)
  3. {
  4. ImageModel image = null;
  5. using (SqlConnection conn = new SqlConnection(connectionString))
  6. {
  7. conn.Open();
  8. SqlCommand cmd = new SqlCommand(“SELECT * FROM Images WHERE Id = @Id”, conn);
  9. cmd.Parameters.AddWithValue(“@Id”, id);
  10. SqlDataReader reader = cmd.ExecuteReader();
  11. if (reader.Read())
  12. {
  13. image = new ImageModel
  14. {
  15. Id = (int)reader[“Id”],
  16. Name = reader[“Name”].ToString(),
  17. ContentType = reader[“ContentType”].ToString(),
  18. Data = (byte[])reader[“Data”]
  19. };
  20. }
  21. }
  22. if (image != null)
  23. {
  24. return File(image.Data, image.ContentType);
  25. }
  26. return HttpNotFound();
  27. }

Step 7: Configure the Connection String

  • Update Connection String:Open Web.config and add your connection string inside the <connectionStrings> section:

xml

  1. <connectionStrings>
  2. <add name=”DefaultConnection” connectionString=”Data Source=YOUR_SERVER;Initial Catalog=ImageUploadDB;Integrated Security=True” providerName=”System.Data.SqlClient” />
  3. </connectionStrings>
  • Update the connectionString variable in the ImageController to use this connection string:

csharp

private string connectionString = ConfigurationManager.ConnectionStrings[“DefaultConnection”].ConnectionString;

Step 8: Run Your Application

  • Start the Application:Press F5 to run your application.
  • Navigate to /Image/Index to access the upload page.
  • Upload an image and see it displayed in the GridView.

Conclusion

Using ASP.NET MVC, you may upload photographs to a SQL Server database and show them in a GridView. The photos are saved as binary data in the database and retrieved for display via an action method that returns the image data as a file. You can improve this implementation by including features like validation, error handling, and user authentication.

Leave a Comment

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