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.
Step 2
Defined in class as like as:
- 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.
- Public HttpPostedFileBase[] ImageUpload{get;set;}
Step 4
Define Razor in VIew,
- @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
-
- if (survey.ImagesUpload.Count() != 0)
- {
-
- foreach (var iten in survey.ImagesUpload)
- {
-
- var fileName = String.Empty;
- if (iten != null)
- {
-
- fileName = Path.GetFileName(iten.FileName);
-
- fileName = fileName.Substring(0, fileName.IndexOf('.')) + "_" + DateTime.Now.Millisecond + "- " + DateTime.Now.Second + "-" + DateTime.Now.Minute + "-" + DateTime.Now.Hour + "." + fileName.Substring(fileName.IndexOf('.') + 1);
-
- var uploadDir = "~/Images";
-
- var imagePath = Path.Combine(Server.MapPath(uploadDir), fileName);
-
- iten.SaveAs(imagePath);
- }
- }
- }