When uploading a file in my MVC site, I\'m looking to handle upload failures due to the user exceeding maxRequestLength more gracefully than for example showing a generic custom
Here's a workaround: set the maxRequestLength
property in your web.config to some high value. Then write a custom validation attribute:
public class MaxFileSize : ValidationAttribute
{
public int MaxSize { get; private set; }
public MaxFileSize(int maxSize)
{
MaxSize = maxSize;
}
public override bool IsValid(object value)
{
var file = value as HttpPostedFileBase;
if (file != null)
{
return file.ContentLength < MaxSize;
}
return true;
}
}
which could be used to decorate your view model with:
public class MyViewModel
{
[Required]
[MaxFileSize(1024 * 1024, ErrorMessage = "The uploaded file size must not exceed 1MB")]
public HttpPostedFileBase File { get; set; }
}
then you could have a controller:
public class HomeController : Controller
{
public ActionResult Index()
{
var model = new MyViewModel();
return View(model);
}
[HttpPost]
public ActionResult Index(MyViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
// TODO: Process the uploaded file: model.File
return RedirectToAction("Success");
}
}
and finally a view:
@model MyViewModel
@using (Html.BeginForm(null, null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.LabelFor(x => x.File)
@Html.ValidationMessageFor(x => x.File)
}