簡體   English   中英

使用C#上傳多個文件時出現問題

[英]Issue in Uploading multiple files using c#

我正在嘗試上傳多個文件(一次單擊即可選擇多個文件並上傳)。 為此,我正在使用以下代碼。 我在MVC4中執行此操作

@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");
}

如果選擇多個文件,則會出現錯誤“超出最大請求長度”,並且當我選擇單個文件並嘗試上傳時,出現錯誤"Object reference not set to an instance of an object" 實際上,我想使用這種相同的形式上傳單個和多個文件。 這怎么可能。 請幫我。 提前致謝。

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

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

對於第二個錯誤,即最大長度超過了Web配置中的更改

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

對於IIS7及更高版本,您還需要添加以下幾行:

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

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM