ASP.NET MVC: Handling upload exceeding maxRequestLength

后端 未结 1 540
盖世英雄少女心
盖世英雄少女心 2021-02-11 07:26

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:40

    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" }))
    {
        <div>
           @Html.LabelFor(x => x.File)
           <input type="file" name="file" />
           @Html.ValidationMessageFor(x => x.File)
        </div>
    
        <p><input type="submit" value="Upload"></p>
    }
    
    0 讨论(0)
提交回复
热议问题