Html helper for <input type="file" />
HTML Upload File ASP MVC 3.
Model: (Note that FileExtensionsAttribute is available in MvcFutures. It will validate file extensions client side and server side.)
public class ViewModel
{
[Required, Microsoft.Web.Mvc.FileExtensions(Extensions = "csv",
ErrorMessage = "Specify a CSV file. (Comma-separated values)")]
public HttpPostedFileBase File { get; set; }
}
HTML View:
@using (Html.BeginForm("Action", "Controller", FormMethod.Post, new
{ enctype = "multipart/form-data" }))
{
@Html.TextBoxFor(m => m.File, new { type = "file" })
@Html.ValidationMessageFor(m => m.File)
}
Controller action:
[HttpPost]
public ActionResult Action(ViewModel model)
{
if (ModelState.IsValid)
{
// Use your file here
using (MemoryStream memoryStream = new MemoryStream())
{
model.File.InputStream.CopyTo(memoryStream);
}
}
}
You can also use:
@using (Html.BeginForm("Upload", "File", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<p>
<input type="file" id="fileUpload" name="fileUpload" size="23" />
</p>
<p>
<input type="submit" value="Upload file" /></p>
}
I had this same question a while back and came across one of Scott Hanselman's posts:
Implementing HTTP File Upload with ASP.NET MVC including Tests and Mocks
Hope this helps.