ASP.NET MVC: Handling upload exceeding maxRequestLength

后端 未结 1 458
孤城傲影
孤城傲影 2021-02-11 07:14

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

1条回答
  •  温柔的废话
    2021-02-11 07:54

    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)

    }

    0 讨论(0)
提交回复
热议问题