【发布时间】:2016-04-06 05:21:48
【问题描述】:
我有一个文件上传页面,在单击按钮时我正在调用一种方法,其中我将最大大小定义为 5 MB。但是当我上传更多内容时,不会显示大小错误消息。这是我的代码:
public ActionResult document(HttpPostedFileBase file, Document model)
{
tbldocument doc = new tbldocument();
//Document model = new Document();
doc.DocumentName = model.documentname;
if (ModelState.IsValid)
{
if (file == null)
{
ModelState.AddModelError("File", "Please Upload Your file");
}
else if (file.ContentLength > 0)
{
int MaxContentLength = 1024 * 1024 * 10; //10 MB
string[] AllowedFileExtensions = new string[] { ".jpg", ".gif", ".png", ".pdf", ".docx", ".doc", ".xml", ".odt", ".xlsx", ".ppt" };
if (!AllowedFileExtensions.Contains(file.FileName.Substring(file.FileName.LastIndexOf('.'))))
{
ModelState.AddModelError("File", "Please file of type: " + string.Join(", ", AllowedFileExtensions));
}
else if (file.ContentLength > MaxContentLength)
{
ModelState.AddModelError("File", "Your file is too large, maximum allowed size is: " + MaxContentLength + " MB");
}
else
{
var fileName = Path.GetFileName(file.FileName);
var path = Server.MapPath("~/App_Data/uploads/documents/" + model.projectid + "");
//var pathFile = path + fileName;
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
var pathWithfileName = Path.Combine(path, fileName);
file.SaveAs(pathWithfileName);
ModelState.Clear();
tbldocument objdb = new tbldocument();
objdb.DocumentName = model.documentname;
objdb.ProjectId = model.projectid;
objdb.Path = model.path;
objdb.Path = Convert.ToString(pathWithfileName);
// objdb.FileName = file.FileName;
//objdb.FileName = file.FileName;
objdoc.upload(objdb);
//" + projectid + "
ViewBag.Message = "File uploaded successfully. File path : ~/Upload/" + fileName;
}
}
}
return RedirectToAction("ProjectTask", "TblTask");
}
【问题讨论】:
-
感谢您编辑@Stephen Muecke
-
该方法是否标有
[HttpPost]?在您的代码中,您永远不会返回视图(您只是重定向),因此添加ModelSateError和ViewBag属性有点毫无意义 -
那我应该返回模型还是文件?我重定向是因为当用户点击上传时,我将重定向到不在同一页面上的文档列表或项目列表
-
我改为从重定向返回视图但同样的错误
-
查看其他答案以获得可能的解决方案。我的评论与您代码中的其他错误有关。如果你添加了一个 ModelStateError
, then you need to check again forModelState` 是无效的,如果是这样,返回视图(你不能调用ModelState.Clear();,因为这只会清除你刚刚添加的所有错误)
标签: c# .net asp.net-mvc localhost