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.
- using System.IO;
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
- //how many image upload this count using count() and if ther is no any file that time this code not execute.
- if (survey.ImagesUpload.Count() != 0)
- {
- //there is multiple image uploaded that time foreach used because iterating this images.
- foreach (var iten in survey.ImagesUpload)
- {
- //here filename variable used because each image name store in that filename
- var fileName = String.Empty;
- if (iten != null)
- {
- //uploaded image filename get using below line
- fileName = Path.GetFileName(iten.FileName);
- //if youwant rename this file this like
- fileName = fileName.Substring(0, fileName.IndexOf('.')) + "_" + DateTime.Now.Millisecond + "- " + DateTime.Now.Second + "-" + DateTime.Now.Minute + "-" + DateTime.Now.Hour + "." + fileName.Substring(fileName.IndexOf('.') + 1);
- //”Images ” this is folder created we are uploading image in that folder
- var uploadDir = "~/Images";
- //your folder name path and image name combined in Server.MapPath()
- var imagePath = Path.Combine(Server.MapPath(uploadDir), fileName);
- //when you have Saveas() call and imagepath as parameter that time this image store in thif Folder.
- iten.SaveAs(imagePath);
- }
- }
- }
Join the conversation! Your thoughts help the community grow.