Showing posts with label Multiple files upload. Show all posts
Showing posts with label Multiple files upload. Show all posts

Monday, 14 April 2014

Asp.Net MVC 4.0 multiple images or files upload application

In  my previous article I have written step by step how to upload image or file. But only one image / file only can be uploaded at one time.

Here I am going to illustrate with sample application how to upload multiple images or files.

Step 1. Add one model class FileUpload as shown below

 public class FileUpload
    {
        public string FileName { get; set; }
        public string Location { get; set; }
        public HttpPostedFileBase File{ get; set; }

    }

Step 2. Add one controller FileUploadController with read write option.

[HttpPost]
        public ActionResult Create(FormCollection collection)
        {
            HttpFileCollectionBase files = HttpContext.Request.Files;
            int fileCount = files.Count;
            try
            {
                for (int index = 0; index < fileCount; index++)
                {
                  HttpPostedFileBase file =   files.Get(index);
                  file.SaveAs("D:\\Test" + file.FileName.Substring(file.FileName.LastIndexOf("\\"),(file.FileName.Length-file.FileName.LastIndexOf("\\"))));
                }
                return RedirectToAction("Index");
            }
            catch(Exception ex)
            {
                return View(ex.Message);
            }
        }


Step 3.  Add view to the Create Get method in controller by right click and select add view. Select strongly type view and select or type complete path of model FileUpload class. Type the below code in view 



@using (Html.BeginForm("Create", "FileUpload", FormMethod.Post, new  { enctype="multipart/form-data"}))
{
        <div class="editor-field">
                @Html.TextBoxFor(model => model.File, new { type = "file", Multiple = "Multiple" })
               
        </div>
         <div class="editor-field">
                @Html.TextBoxFor(model => model.File, new { type = "file", Multiple = "Multiple" })
               
        </div>
     <div class="editor-field">
                @Html.TextBoxFor(model => model.File, new { type = "file", Multiple = "Multiple" })
               
        </div>
        <p>
            <input type="submit" value="Create" />
        </p>
}

Step 4. Create D:\\Test folder.Give permission and remove read only attribute.

Now run and select and save the files.