2016-11-30 43 views
1

這裏是我的HTML:C#/ MVC - 當表單包含多個文件輸入時如何遍歷多個文件(從文件輸入)?

<input id="openbox_actual" class="btn btn-lg btn-warning" type="file" name="videoFile" style="display: none;" /> 
<input id="openbox_actual2" class="btn btn-lg btn-warning" type="file" accept="image/*" name="screenShots" multiple="multiple" style="display: none;" /> 

如上圖所示,一個文件輸入需要的視頻文件,以及其他需要多個圖像文件。

這裏的控制器:

HttpPostedFileBase file = Request.Files["videoFile"]; 
HttpPostedFileBase screens = Request.Files["screenShots"]; 

從上面的代碼,我可以訪問/上傳「文件」就好了。

但是,我不知道如何訪問「屏幕」內的所有文件只有

我見過很多例子,人們在每個文件輸入中迭代「HttpPostedFileCollection」,但包含所有文件。我只想從「screenShots」多個文件輸入中獲取所有文件。如果有誰知道如何「限」的文件,以8(

由於數量如這裏的「屏幕截圖」文件輸入只允許你上傳8個文件總計, 你們是偉大的

加分!

回答

1

可以使用GetKey爲給定的指標得到名字

for(int i = 0 ; i < this.Request.Files.Count; i++) { 

    String key = this.Request.Files.GetKey(i); 

    if(key == "screenShots") { 
     // do stuff 
    } 
} 

你可以做到這一點作爲一種別處前工序可以重複使用的:

public static Dictionary<String,List<HttpPostedFileBase>> GetFilesAsDictionary(HttpFileCollection files) { 

    Dictionary<String,List<HttpPostedFileBase>> dict = Dictionary<String,List<HttpPostedFileBase>>; 

    for(int i = 0 ; i < files.Count; i++) { 
     String key = file.GetKey(i); 

     List<HttpPostedFileBase> list; 

     if(!dict.TryGetValue(key, out list)) { 
      dict.Add(key, list = new List<HttpPostedFileBase>()); 
     } 

     list.Add(files[i]); 
    } 

    return dict; 
} 

用法:

[HttpPost] 
public ActionResult MyAction() { 

    Dictionary<String,List<HttpPostedFileBase>> files = UploadUtility.GetFilesAsDictionary(this.Request.Files); 

    HttpPostedFileBase video = files["videoFile"][0]; 
    Int32 screenshotCount = files["screenShots"].Count; 
    if(screenshotCount > 8) { 
     this.ModelState.AddModelError("", "Limit of 8 screenshots at a time."); 
     return this.View(new VideModel()); 
    } 

    foreach(HttpPostedFileBase screenshot in files["screenShots"]) { 
     // do stuff 
    } 
} 
+0

謝謝你,你釘它!把它從公園裏擠出來。走的路,以及偉大的響應時間!如果我們在打棒球,而且我需要一個鈴聲來衝出一個公園,那麼你將成爲我的第一個選擇。再次感謝。 :-) – Penjimon

相關問題