2013-12-16 76 views
0

我想上傳多個文件,(在一次單擊和上傳中選擇多個文件)。爲此,我使用下面的代碼。我在MVC4這樣使用C上傳多個文件的問題#

@using (Html.BeginForm("Gallery", "Admin", FormMethod.Post, new {enctype="multipart/form-data", id = "GalleryForm" })) 
     { 
      @Html.ValidationSummary(); 

      <div> Select the files to Upload<br /> <input type="file" name="file" id="file" multiple="multiple" /><br /><br /></div> 
      <div><input type="submit" name="submit" Value="Save"/></div> 
     } 

控制器

[HttpPost] 
    public ActionResult Gallery(IEnumerable<HttpPostedFileBase> files) 
    { 
     foreach (var file in files) 
     { 
      if (file.ContentLength > 0) 
      { 
       var fileName = Path.GetFileName(file.FileName); 
       var path = Path.Combine(Server.MapPath("~/Images/Gallery/"), fileName); 
       file.SaveAs(path); 
      } 
     } 
     return RedirectToAction("Index"); 
    } 

如果我選擇多個文件,我得到了錯誤「最大請求長度超過了」當我selecet單一的文件,並嘗試然後上傳我出現錯誤「未將對象引用設置爲對象的實例」。其實我想用同樣的形式上傳單個和多個文件。怎麼可能。請幫幫我。在此先感謝

+0

需要更多信息:顯示的代碼行是否顯示錯誤?這可能是foreach ..因爲參數名稱不匹配而爲空的文件。另請參閱此問題:http://stackoverflow.com/questions/8356506/how-to-write-html-beginform-in-razor和http://stackoverflow.com/questions/4232347/multiple-file-upload-using -request-filesfiles -mvc –

+0

@DaviddCeFreitas:我想用「單輸入控制」上傳多個文件 – neel

回答

0

您的參數名稱與您的表單輸入元素名稱不匹配,您應該在後面的代碼和html中使用「文件」或「文件」。 name="file"應該是name="files"

+0

有時候我想用這個輸入控件上傳多個文件。但是這個代碼只允許上傳一個文件 – neel

1

重命名你的輸入類型的文件name屬性

<input type="file" name="files" id="file" multiple="multiple" /> 

對於第二個錯誤,即maximunn長度超過web配置

<configuration> 
    <system.web> 
     <httpRuntime maxRequestLength="1048576" /> 
    </system.web> 
</configuration> 

對於IIS7及以上的,你還需要添加以下線的變化:

<system.webServer> 
    <security> 
     <requestFiltering> 
     <requestLimits maxAllowedContentLength="1073741824" /> 
     </requestFiltering> 
    </security> 
</system.webServer> 

注意:maxAllowedContentLength是measure d以字節爲單位,而maxRequestLength以千字節爲單位,這就是配置示例中值不同的原因。 (兩者相當於1 GB)