如何在保存之前使用ContentLength检查文件的大小,如在服务器(MVC4)中

时间:2014-08-03 15:12:21

标签: asp.net-mvc-4

我的错误是Maximum request length exceeded. 我希望文件上传必须小于2MB。请帮我修改代码,谢谢

我的控制员:

public ActionResult Index()
        {
            var path = "~/Images/upload/";

            if (Request.Files["UpFile"] != null && Request.Files["UpFile"].ContentLength < 2048)
            {
                var upload = Request.Files["UpFile"];
                upload.SaveAs(Server.MapPath(path + upload.FileName));
            }
            else
            {
                ModelState.AddModelError("", "The size of file too big");
            }

            return View();
        }

1 个答案:

答案 0 :(得分:1)

尝试管理最大请求长度,以便将错误减少到最小: Maximum request length exceeded

我认为即使您有全局异常处理程序,在使用上传文件时也可以使用try..catch。