Rafael León
Rafael León

Reputation: 81

Select folder in ASP.NET MVC application to upload files

If I want upload a file it's simply:

Razor

@Html.TextBoxFor(m => m.File, new { type = "file" })

or

Html

<input type="file">

But, If I want select a folder to upload all files than contains, is it possible?

Something like:

Razor

@Html.TextBoxFor(m => m.Folder, new { type = "folder" })

Showing a "select folder dialog".

Upvotes: 1

Views: 5490

Answers (1)

Jack
Jack

Reputation: 1493

You can't do that when using @Html.TextBoxFor. There may be another way to upload a folder, but I don't know of it.

However, you can change the file upload dialog to upload multiple files at once, which is essentially the same thing. Here is a tutorial showing how.

Essentially, you need to add the following attribute to your file upload input:

@Html.TextBoxFor(m => m.File, new { type = "file", @multiple = "multiple"  })

You also need to add the multpart/form-data attribute to your Razor code to generate the form. Here is an example from that tutorial:

@using (Html.BeginForm("UploadFiles", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))

At this point, you can select multiple files to upload. You can easily open the folder, hit CTRL+A to select all, then hit upload to upload the entire folder at once.

Please note that you'll need to modify the controller action to accept multiple files at once.

EDIT: Here is an example on how to handle this in your controller action, from the previously mentioned tutorial. Note that your parameter is an array of HttpPostedFileBase objects, each one representing a file you upload. Then, you iterate through each and save it.

[HttpPost]  
public ActionResult UploadFiles(HttpPostedFileBase[] files)  
{  

    //Ensure model state is valid  
    if (ModelState.IsValid)  
    {   //iterating through multiple file collection   
        foreach (HttpPostedFileBase file in files)  
        {  
            //Checking file is available to save.  
            if (file != null)  
            {  
                var InputFileName = Path.GetFileName(file.FileName);  
                var ServerSavePath = Path.Combine(Server.MapPath("~/UploadedFiles/") + InputFileName);  
                //Save file to server folder  
                file.SaveAs(ServerSavePath);  
            }    
        }  
    }  
    return View();  
}  

Upvotes: 3

Related Questions