我創建了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