Upload multiple file in mvc

 

# Upload multiple file in mvc

Note:- Fundamentals of uploading multiple file is same as uploading single file, so just follow previous post of file upload (click on mvc menu at website and find the link of file upload in mvc ). we need just two changes in file upload application ,first is in method now we use foreach loop in basic code and second change will be in view,use multiple attribute of textbox.   

Replace the code of .Upload a File in MVC application with these two file respectively


UploadFile.Cshtml


@{
    ViewBag.Title = "UploadFile";
}
<h2>UploadFile</h2>
 
@using (Html.BeginForm("UploadFile", "FileUploading", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    <div>
        <br />
        <input type="file" id="files" name="files" multiple>
        <input type="submit" value="Upload" />
        @ViewBag.Message
    </div>
}





FileUploadingController.cs


using System.IO;
using System.Web;
using System.Web.Mvc;
 
namespace FileUpload.Controllers
{
    public class FileUploadingController : Controller
    {
        // GET: FileUploading
 
        public ActionResult UploadFile()
        {
            return View();
        }
 
        [HttpPost]
        public ActionResult UploadFile(HttpPostedFileBase[] files)
        {
            try
            {
                foreach (HttpPostedFileBase file in files) {
                    if (file.ContentLength > 0)
                    {
                        string fileName = Path.GetFileName(file.FileName);
                        string path = Path.Combine(Server.MapPath("~/UploadedFiles"), fileName);
                        file.SaveAs(path);
                    }
                }
                ViewBag.Message = "File Uploaded Successfully!!";
                return View();
            }
            catch
            {
                ViewBag.Message = "File upload failed!!";
                return View();
            }            
        }
    }
}


No comments:

Post a Comment