Image Upload In MVC Using Razor Control

There are multiple ways you can upload images in C# and in HTML. If we choose HTML then we should use “File input tag”. This Image can be accessed in Controller using HttpPostedFileBase class using the file name.
 
Step 1
 
The class is defined as System.IO namespace. You must import this namespace before using the class.
  1. using System.IO;  
Step 2
 
Defined in class as like as:
  1. Public  HttpPostedFileBase ImageUpload {get;set;}  
Step 3
 
If we want multiple images at a time, we need to define the empty array in HttppostedFile with the array.
  1. Public  HttpPostedFileBase[] ImageUpload{get;set;}  
Step 4
 
Define Razor in VIew,
  1. @Html.TextBoxFor(m => m.ImagesUpload, new { type = "file"multiple = "multiple"accept = "image/jpeg,  image/jpg" })  
In the above code, type is "File" and if you want multiple images that time Multiple=”multiple” option is used, in which extension type of image uploading is .jpg, .jpeg,.png and so on.
 
Here is the complete code,
 
Sample Code
  1. //how many image upload this count using count() and if  ther is no any file that time this code not execute.  
  2. if (survey.ImagesUpload.Count() != 0)  
  3.  {  
  4.     //there is multiple image uploaded that time foreach used because iterating this images.  
  5.      foreach (var iten in survey.ImagesUpload)  
  6.      {  
  7.           //here filename variable used because each image name store in that filename  
  8.           var fileName = String.Empty;  
  9.           if (iten != null)  
  10.           {  
  11.                 //uploaded image filename get using below line  
  12.                   fileName = Path.GetFileName(iten.FileName);  
  13.                 //if youwant rename this file this like  
  14.                   fileName = fileName.Substring(0, fileName.IndexOf('.')) + "_" + DateTime.Now.Millisecond + "-                                       " + DateTime.Now.Second + "-" + DateTime.Now.Minute + "-" + DateTime.Now.Hour + "." + fileName.Substring(fileName.IndexOf('.') + 1);  
  15.                 //”Images ” this is folder created we are uploading image in that folder  
  16.                 var uploadDir = "~/Images";  
  17.                 //your folder name path and image name combined in Server.MapPath()  
  18.                 var imagePath = Path.Combine(Server.MapPath(uploadDir), fileName);  
  19.                 //when you have Saveas() call and imagepath as parameter that time this image store in thif Folder.  
  20.                 iten.SaveAs(imagePath);  
  21.           }  
  22.     }  
  23. }