2016-11-30 87 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