简体   繁体   English

如何正确编写一个foreach循环以在ASP.NET C#中上传多个文件

[英]How do you properly write a foreach loop to upload multiple files in asp.net C#

I have seen this style demo'ed on many sites as a way to upload multiple files in asp.net, but I cannot get it to work. 我已经在许多网站上看到了这种样式的演示,它是一种在asp.net中上传多个文件的方法,但是我无法使其正常工作。 If I select 6 files, it only ends up saving one file, but the label shows 6 filenames of the same name. 如果选择6个文件,则最终只会保存一个文件,但是标签显示6个同名文件名。 WHen I debug, it shows each file name on each loop like I would want it to. 当我调试时,它会像我希望的那样在每个循环中显示每个文件名。 Why is it not working? 为什么不起作用?

Also, I have an update panel on the page if that matters. 另外,如果重要的话,页面上还会有一个更新面板。

I am using an asp.net upload control with multiple uploads turned on. 我正在使用具有多个上载功能的asp.net上传控件。 I know the paths are correct because it works perfect when I upload only one file. 我知道路径是正确的,因为当我仅上传一个文件时,它可以完美工作。

string Path = Request.Url.AbsolutePath;
string ProperPath = Path.Replace(@"Pages/InsertVideo.aspx", @"TrainingMaterial/Video/");

if (FileUpload1.HasFiles) { 
    //SaveFile(FileUpload1.PostedFile);

    foreach (HttpPostedFile File in FileUpload1.PostedFiles)
    {
        FileUpload1.SaveAs(System.IO.Path.Combine(Server.MapPath(ProperPath), FileUpload1.FileName));
        lblFilesUploaded1.Text += String.Format("{0}<br />", FileUpload1.FileName);
    }
}

I also tried this technique with same results as above. 我也尝试了这种技术,其结果与上述相同。 Any advice? 有什么建议吗? I am thinking it has to do with my SaveAs string. 我认为这与我的SaveAs字符串有关。

foreach (string key in Request.Files)
{
    HttpPostedFile file = Request.Files[key];
    if (file.ContentLength != 0)
    {
        file.SaveAs(System.IO.Path.Combine(Server.MapPath(ProperPath), FileUpload1.FileName));
    }
}

This shoud do the trick: 应该做到这一点:

if (FileUpload1.HasFiles)
{
    foreach (var file in FileUpload1.PostedFiles)
    {
        file.SaveAs(Path.Combine(Server.MapPath(ProperPath), file.FileName));
        lblFilesUploaded1.Text += String.Format("{0}<br />", file.FileName);
    }
}

In your solution you are referring in the foreach always the FileUpload control not the current uploaded file. 在您的解决方案中,您始终在foreach中引用FileUpload控件,而不是当前上传的文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM