ASP.NET MVC > Entity Framework

Upload multiple files on server in ASP.NET MVC

How to upload multiple files on server in ASP.NET MVC?


Before proceeding with this example, it is recommended to learn how to upload a single file on the server in the previous examples.

To upload multiple file, we will follow the same approach as we followed for single file upload however the way to access the form file element in action method would be little different.

VIEW CODE

<h3>Upload multiple files</h3>
@using (Html.BeginForm("UploadMultipleFiles", "Files", FormMethod.Post, 
new { enctype = "multipart/form-data" })
) { @Html.AntiForgeryToken() @Html.Hidden("FileName", "False data") <div class="form-horizontal"> <h4>Files</h4> <hr /> @Html.ValidationSummary(true, "", new { @class = "text-danger" }) <div class="form-group"> @Html.LabelFor(model => model.FileName, htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> <input type="file" name="fileNames" class="form-control" multiple />
<input type="file" name="fileNames" class="form-control" multiple />
</div> </div> <div class="form-group"> @Html.LabelFor(model => model.Active, htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> <div class="checkbox"> @Html.EditorFor(model => model.Active) @Html.ValidationMessageFor(model => model.Active, "", new { @class = "text-danger" }) </div> </div> </div> <div class="form-group"> <div class="col-md-offset-2 col-md-10"> <input type="submit" value="Upload Multiple" formnovalidate class="btn btn-default" /> </div> </div> </div> }

In the above code snippet, we have more than one html file upload element (and also have kept multiple attribute that supports only in HTML 5 - this ensures that a single HTML file element enable user to select multiple file by holding ctrl key) and remaining codes are same as last point of uploading a single file on the server. When this form will be submitted, it will go to UploadMultipleFiles action method of the controller. Notice that the name ("fileNames") of the file upload elements are same.

CONTROLLER ACTION METHOD

[HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult UploadMultipleFiles([Bind(Include =
"AutoId,FileName,Active,PersonalDetailsId")] Files files,
IEnumerable<HttpPostedFileBase> fileNames)
        {
            if (ModelState.IsValid)
            {

                // upload the file now
                string path = Server.MapPath("~/UserData/");
                //string selectedFileName =
System.IO.Path.GetFileName(FileName.FileName);

                foreach (HttpPostedFileBase file in fileNames)
                {
                    if (file.ContentLength > 0) // if file selceted then save
                    {
                        // get extension name of the selcted file
                        string extensionName =
System.IO.Path.GetExtension(file.FileName);
                        // generate a random file name and appende extension name
                        string finalFileName = DateTime.Now.Ticks.ToString() +
extensionName;
                        // now save the selected file with new name
file.SaveAs(path + finalFileName);

                        // set the final file name to the files object so the name
would get saved into the database
                        files.FileName = finalFileName;
                        db.Files.Add(files);
                        db.SaveChanges();
                     }
                 }
                 return RedirectToAction("Index");
             }   

             return View("Create", files);
        }

In this action method notice the 2nd parameter that is IEnumerable of HttpPostedFileBase because the form sends more than one form file element, also the name of this parameter must be exactly same as the name of the form file element.

After validating the ModelState, we are iterating through each File element of the form and checking for its length to ensure that file upload code only executes when user has selected any file. Once the file content length validation is passed, we get the extension name, random file name and saves the file on the server and then set its name into the Files property and call the SaveChanges method.

 Views: 22003 | Post Order: 105



Write for us






Hosting Recommendations