2010-12-06 43 views
2

我創建了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。我該怎麼辦?

回答

1

maxRequestLength的是在千字節(KB)。您的設置爲2000KB(略低於2MB,因爲1MB中有1024KB)。

我不知道爲什麼它工作在某些瀏覽器,而不是別人,除非是一些正在壓縮的整個上載內容和其他人都沒有(我相信是支持HTTP 1.1)。

HTH, 布賴恩

1

試試這個。這段代碼已經過測試並按預期工作。將來不要使用var類型作爲字符串變量。 var是一個動態類型,應該適用於所有文件類型 - 包括數組。但嘗試具體的文件類型將有助於減少錯誤。

我通常保持公共文件夾中的我的公開文件中。因此,將其更改爲您的文件夾(如程序App_Data)

[HttpPost] 
public ActionResult test(HttpPostedFileBase file) 
{ 
    if (file.ContentLength> 4096000) 
     { 
      return RedirectToAction ("FileTooBig"); 
     } 

    string fileName = Path.GetFileName(file.FileName); 
    string uploadPath = Server.MapPath("~/Public/uploads/" + fileName); 

    file.SaveAs(uploadPath); 
    return View("Index"); 
} 

好運

+0

我需要在上傳前檢查文件大小。我可以在Global.asax中的Application_BeginRequest事件中做到這一點,但如果size大於我的變量maxFileSize,如何取消下載文件?如果我在此事件中使用重定向,則首先加載文件,然後再重定向。 – Stwr 2010-12-06 18:55:24

+0

如果沒有http請求,則無法檢查文件。注意actionResult方法之上的[httpPost]需要提交輸入。一旦提交,httpPostFileBase正在等待處理。現在,您可以使用自己的邏輯對文件進行任何操作。 – Jack 2010-12-06 19:52:06

0

然後嘗試使用,如果最別人。此片段有效。如果你喜歡它,給我投票。需要

[HttpPost] 
public ActionResult test(HttpPostedFileBase file) 
{ 
    if (file.ContentLength > 400) 
    { 
     return RedirectToAction("GeneralError", "Error"); 
    } 
    else 
    { 
     string fileName = Path.GetFileName(file.FileName); 
     string uploadPath = Server.MapPath("~/Public/uploads/" + fileName); 

     file.SaveAs(uploadPath); 
     return View("Index"); 
    } 
} 

兩個輸入按鈕: 對於瀏覽文件: 提交文件:

祝您好運!

1

無法阻止文件上傳。 IIS在將它傳遞給ASP.NET堆棧之前接收整個HTTP請求主體。這包括您的多部分表單帖子的所有部分。由於這個ASP.NET確實沒有機會通過檢查file.ContentLength屬性來中斷文件上傳。

可以編寫自定義HTTP模塊查詢的文件大小,但中止或關閉在一個空的響應接收到整個請求結果之前的響應。意味着沒有辦法優雅地失敗。

我的建議是做這樣的文件上傳在一個隱藏的iframe,同時實現HTTP模塊。這樣,如果出現問題,您的主頁不會中斷。

每個人都可以與我一起感謝微軟爲這真棒「功能」(在諷刺隊列)。

謝謝微軟。謝謝。