我创建了mvc项目并希望上传文件。我在web.config带有httpRuntime的mvc文件上传maxRequestLength
<httpRuntime maxRequestLength="2000"/>
<customErrors mode="On" redirectMode="ResponseRedirect" defaultRedirect="address here"> </ customErrors>, in Index.aspx <% using (Html.BeginForm ("upload", "home", FormMethod.Post,
new {enctype = "multipart/form-data"})) {%>
<label for="file"> Filename: </ label>
<input type="file" name="file" id="file" />
<input type="submit" />
<%}%>
登记在HomeController.cs
[HttpPost]
public ActionResult Upload (HttpPostedFileBase file)
{
if (file! = null & & file.ContentLength> 0)
{
if (file.ContentLength> 4096000)
{
return RedirectToAction ("FileTooBig");
}
var fileName = Path.GetFileName (file.FileName);
var path = Path.Combine (Server.MapPath ("~/App_Data/uploads"), fileName);
file.SaveAs (path);
}
return RedirectToAction ("Index");
}
如果我附加文件超过2兆字节的defaultRedirect完美的作品在Opera,但在Chrome和IE浏览器无法正常工作。我还在Global.asax的Application_Error()事件中使用了Response.Redirect(“address here”)。它也不适用于Chrome和IE。我该怎么办?
我需要在上传前检查文件大小。我可以在Global.asax中的Application_BeginRequest事件中做到这一点,但如果size大于我的变量maxFileSize,如何取消下载文件?如果我在此事件中使用重定向,则首先加载文件,然后再重定向。 – Stwr 2010-12-06 18:55:24
如果没有http请求,则无法检查文件。注意actionResult方法之上的[httpPost]需要提交输入。一旦提交,httpPostFileBase正在等待处理。现在,您可以使用自己的逻辑对文件进行任何操作。 – Jack 2010-12-06 19:52:06