In a project I’m working on, I needed to implement a file upload in ASP.NET MVC. There are basically two ways to implement it:
- Handle the upload of the file in the view itself.
- Handle it in the controller.
The code for both of them is pretty similar.
First you need to have a file input in your view:
@Html.BeginForm("ActionName", "ControllerName", FormMethod.Post, new { enctype = "multipart/form-data"})
{
<input type="file" name="uploadedFile" value="Browse">
<input id="uploadbutton" type="submit" value="Upload">
}
If you want to handle it all in the view itself, you can also use null as action and controller name and add the following at the beginning of your view:
@{
if (IsPost)
{
HttpPostedFileBase uploadedFile = Request.Files[0];
if (uploadedFile != null)
{
string fileName = Path.GetFileName(uploadedFile.FileName);
if (!string.IsNullOrWhiteSpace(fileName))
{
string directory = AppDomain.CurrentDomain.BaseDirectory + @"App_Data\UploadedFiles";
string fileSavePath = directory + "\\" + fileName;
Directory.CreateDirectory(directory);
uploadedFile.SaveAs(fileSavePath);
}
}
}
}
In case you want to handle it in the controller, you should provide the right controller name and action name e.g. Index:
@Html.BeginForm("Index", "File", FormMethod.Post, new { enctype = "multipart/form-data"})
Then in your controller create an Index method which will handle the file upload:
public class FileController : Controller
{
// GET
public ActionResult Index()
{
return View();
}
// POST
[HttpPost]
public ActionResult Index(HttpPostedFileBase uploadedFile)
{
if (uploadedFile != null)
{
string fileName = Path.GetFileName(uploadedFile.FileName);
if (!string.IsNullOrWhiteSpace(fileName))
{
string directory = AppDomain.CurrentDomain.BaseDirectory + @"App_Data\UploadedFiles";
string fileSavePath = directory + "\\" + fileName;
Directory.CreateDirectory(directory);
uploadedFile.SaveAs(fileSavePath);
}
}
return RedirectToAction("Index");
}
}
That’s it ! If you want to handle multiple file uploads e.g. to allow a user to upload a resume, a motivation letter, a degree… it’s damned easy.
In case you went for the solution in the view, you just have to iterate through Request.Files.
If you went for the solution in the controller, just change the signature of your action to take an enumerable instead of a single HttpPostedFileBase:
public ActionResult Index(IEnumerable<HttpPostedFileBase> uploadedFile)
Then iterate through the enumeration and save each file.