【问题标题】:C#/MVC - How to loop through Multiple Files (from a file input), when the form contains multiple file inputs?C#/MVC - 当表单包含多个文件输入时,如何循环多个文件(从文件输入)?
【发布时间】:2016-11-30 01:42:14
【问题描述】:

这是我的 HTML:

<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 个,则加分。(例如,“screenShots”文件输入仅允许您总共上传 8 个文件。

谢谢, 你们太棒了!

【问题讨论】:

    标签: c# html .net razor


    【解决方案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
        }
    }
    

    【讨论】:

    • 谢谢,你成功了!把它赶出公园。路要走,响应时间长!如果我们在打棒球,而我需要一个振铃器将一个人从公园里炸出来,那么你将是我的第一选择。再次感谢。 :-)
    猜你喜欢
    • 1970-01-01
    • 2015-03-19
    • 1970-01-01
    • 2012-06-14
    • 1970-01-01
    • 2011-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多