Saturday, August 10, 2019

How to upload image to database and show in a Page without image handler in MVC4

Step - 1 : Create New Project.

Go to File > New > Project > Select asp.net MVC4 web application > Entry Application Name > Click OK > Select Internet Application > Select view engine Razor > OK

Step-2: Add a Database.

Go to Solution Explorer > Right Click on App_Data folder > Add > New item > Select SQL Server Database Under Data > Enter Database name > Add.

Step-3: Create table for fetch data.

Open Database > Right Click on Table > Add New Table > Add Columns > Save > Enter table name > Ok. 
In this example, I have used one tables as below

Step-4: Add Entity Data Model.

Go to Solution Explorer > Right Click on Project name form Solution Explorer > Add > New item > Select ADO.net Entity Data Model under data > Enter model name > Add.
A popup window will come (Entity Data Model Wizard) > Select Generate from database > Next >

Chose your data connection > select your database > next > Select tables > enter Model Namespace > Finish. 

Step-5: Make changes on model for enable file upload.

Open your model and do change as below. Here I have added one new Public property of type HttpPostedFileBase. Please follow below code 

  1. using System.ComponentModel.DataAnnotations;
  2. using System.Web;
  3. public partial class ImageGallery
  4. {
  5. public int ImageID { get; set; }
  6. public int ImageSize { get; set; }
  7. public string FileName { get; set; }
  8. public byte[] ImageData { get; set; }
  9. [Required(ErrorMessage = "Please select file")]
  10. public HttpPostedFileBase File { get; set; }
  11. }

Step-6: Create a Controller .

Go to Solution Explorer > Right Click on Controllers folder form Solution Explorer > Add > Controller > Enter Controller name > Select Templete "empty MVC Controller"> Add.


Step-7: Add new action into your controller for fetch images from database and show in view.

Here I have added "Gallery" Action into "ImageGallery" Controller. Please write this following code 

  1. public class ImageGalleryController : Controller
  2. {
  3. public ActionResult Gallery()
  4. {
  5. List<ImageGallery> all = new List<ImageGallery>();
  6. // Here MyDatabaseEntities is our datacontext
  7. using (MyDatabaseEntities dc = new MyDatabaseEntities())
  8. {
  9. all = dc.ImageGalleries.ToList();
  10. }
  11. return View(all);
  12. }
  13. }

Step-8: Add view for Gallery Action & design for Show Images from database.

[N:B: Before going to add view, please rebuild solution.]


Right Click on Action Method (here right click on Gallery action) > Add View... > Enter View Name > Select View Engine (Razor) > Check "Create a strong-typed view" > Select your model class > Select scaffold templete "List" > Add. 
HTML Code 
  1. @model List<MVCImageGallery.ImageGallery>
  2. @{
  3. ViewBag.Title = "Gallery";
  4. }
  5. <h2>Gallery</h2>
  6. <p>
  7. @Html.ActionLink("Upload New", "Upload")
  8. </p>
  9. @* Here I will show Uploaded Images *@
  10. <table>
  11. @{
  12. int j = 0;
  13. for (int i = 0; i < Model.Count(); i+=4)
  14. {
  15. j = i;
  16. <tr>
  17. @* I have done this for show 4 images in a Row *@
  18. @while (j < i+4 && j < Model.Count())
  19. {
  20. <td>
  21. <img src="data:image/png;base64,@Convert.ToBase64String(Model[j].ImageData,0,Model[j].ImageData.Length)" width="100" />
  22. </td>
  23. j++;
  24. }
  25. </tr>
  26. }
  27. }
  28. </table>

Step-9: Add another new action into your controller for Get Method for upload image to the database

Here I have added "Upload" Action into "ImageGalleryController" Controller. Please write this following code 

  1. public ActionResult Upload()
  2. {
  3. return View();
  4. }

Step-10: Add view for action "Upload" for upload image.

Right Click on Action Method (here right click on Upload action) > Add View... > Enter View Name > Select View Engine (Razor) > Check "Create a strong-typed view" > Select your model class > Select scaffold templete "Create" > Add. 

  1. @model MVCImageGallery.ImageGallery
  2. @{
  3. ViewBag.Title = "Upload";
  4. }
  5. <h2>Upload</h2>
  6. @using (Html.BeginForm("Upload","ImageGallery", FormMethod.Post,new{enctype="multipart/form-data"}))
  7. {
  8. @Html.ValidationSummary(true)
  9. <table>
  10. <tr>
  11. <td>Select File : </td>
  12. <td>
  13. @Html.TextBoxFor(Model=> Model.File, new{type="file"})
  14. @Html.ValidationMessage("CustomError")
  15. </td>
  16. <td>
  17. <input type="submit" value="Upload" />
  18. </td>
  19. </tr>
  20. </table>
  21. }
  22.  
  23. @section Scripts {
  24. @Scripts.Render("~/bundles/jqueryval")
  25. }

Step-11: Add new action into "ImageGallery" controller for POST Method for upload image to the database.

Here I have added "Upload" Action with Model Parameter (here "ImageGallery") into "ImageGallery" Controller. Please write this following code 

  1. [HttpPost]
  2. public ActionResult Upload(ImageGallery IG)
  3. {
  4. // Apply Validation Here
  5.  
  6. if (IG.File.ContentLength > (2*1024*1024))
  7. {
  8. ModelState.AddModelError("CustomError", "File size must be less than 2 MB");
  9. return View();
  10. }
  11. if (!(IG.File.ContentType == "image/jpeg" || IG.File.ContentType == "image/gif"))
  12. {
  13. ModelState.AddModelError("CustomError", "File type allowed : jpeg and gif");
  14. return View();
  15. }
  16.  
  17. IG.FileName = IG.File.FileName;
  18. IG.ImageSize = IG.File.ContentLength;
  19.  
  20. byte[] data = new byte[IG.File.ContentLength];
  21. IG.File.InputStream.Read(data, 0, IG.File.ContentLength);
  22.  
  23. IG.ImageData = data;
  24. using (MyDatabaseEntities dc = new MyDatabaseEntities())
  25. {
  26. dc.ImageGalleries.Add(IG);
  27. dc.SaveChanges();
  28. }
  29. return RedirectToAction("Gallery");
  30. }
Step-12: Run Application.

No comments:

Post a Comment

How to register multiple implementations of the same interface in Asp.Net Core?

 Problem: I have services that are derived from the same interface. public interface IService { } public class ServiceA : IService { ...