Request.Files同样的文件上传asp.net mvc

时间:2014-05-25 16:19:47

标签: c# asp.net-mvc twitter-bootstrap file-upload

            foreach (string fileName in Request.Files)
            {
                HttpPostedFileBase file = Request.Files[fileName];

                //Save file content goes here
                fName = file.FileName;
                if (file != null && file.ContentLength > 0)
                {


                    subPath = ConfigurationManager.AppSettings["SubPath"].ToString() + "/" + currentUserId;
                    bool isExists = System.IO.Directory.Exists(Server.MapPath(subPath));

                    if (!isExists)
                        System.IO.Directory.CreateDirectory(Server.MapPath(subPath));


                    string path = System.IO.Path.Combine(Server.MapPath(subPath), System.IO.Path.GetFileName(file.FileName));
                    file.SaveAs(path);



                }

            }

如果我上传多个文件,我会得到相同的文件n次。

我正在使用此控件:https://github.com/kartik-v/bootstrap-fileinput

我的cs.html

http://codepen.io/anon/pen/aekqm

请在上面找到我的完整代码。

3 个答案:

答案 0 :(得分:8)

解决了我的问题:

使用下面的代码

for (int i = 0; i < Request.Files.Count; i++)
{
    HttpPostedFileBase file = Request.Files[i];
}

而不是两次使用相同文件的foreach循环

答案 1 :(得分:2)

根据this site

  

从单个文件控件上传多个文件时,会为它们分配相同的名称。

答案 2 :(得分:1)

改变这个:

<input id="file-3" name="files" type="file" multiple>

到此:

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

或:

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