How to upload Multiple File in ASP.NET MVC

By FoxLearn 11/13/2024 1:42:16 AM   76
In ASP.NET MVC, uploading multiple files can be done easily using the HttpPostedFileBase class.

You can create a view model to represent the file upload. This step is optional, but it will make it easier to bind the data in the controller.

public class FileUploadViewModel
{
    public IEnumerable<HttpPostedFileBase> Files {get;set;}
}

In your controller, you can create an action to show the file upload form.

For example, create a FileUploadController and add an action to display the view.

public class FileUploadController : Controller
{
    // Display the upload form
    public ActionResult Index()
    {
        return View();
    }

    // Handle file upload
    [HttpPost]
    public ActionResult Upload(FileUploadViewModel model)
    {
        if (model.Files != null)
        {
            foreach (var file in model.Files)
            {
                if (file != null && file.ContentLength > 0)
                {
                    // Generate a unique file name and save it to a location
                    var fileName = Path.GetFileName(file.FileName);
                    var path = Path.Combine(Server.MapPath("~/files"), fileName);
                    file.SaveAs(path);
                }
            }
            ViewBag.Message = "Files uploaded successfully.";
        }
        else
        {
            ViewBag.Message = "No files selected.";
        }
        return View("Index");
    }
}

Now, create a view to display the file upload form.

@model YourNamespace.FileUploadViewModel
@{
    ViewBag.Title = "Upload Multiple Files";
}

<h2>Upload Multiple Files</h2>
@using (Html.BeginForm("Upload", "FileUpload", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    <div>
        <label>Select Files:</label>
        <input type="file" name="Files" multiple="multiple" />
    </div>
    <div>
        <button type="submit">Upload</button>
    </div>
}
@if (ViewBag.Message != null)
{
    <div>@ViewBag.Message</div>
}

In the Upload POST action in your controller, you handle the file saving logic. Each file is saved with its original file name in the ~/files directory on the server.