0

如果任何文件上传控件不包含有效扩展,我该如何停止在以下代码中上传文件?例如,如果第一个控件中的文件包含有效的扩展名但第二个控件的扩展名无效,那么我想停止上传文件并中断操作。

List<string> validExtensions = new List<string> { ".jpg", ".jpeg", ".png", ".stl" };        
for (int i = 0; i <= hfc.Count - 1; i++)
    {
        string guidResult = System.Guid.NewGuid().ToString();

        HttpPostedFile hpf = hfc[i];
        string extension = Path.GetExtension(hfc[i].FileName);
        if (hpf.ContentLength > 0)
        {
            if (!validExtensions.Contains(extension.ToLower()))
            {
                lblMsg.Text = "Extension not supported";

            }
            else
            {
                hpf.SaveAs(Server.MapPath("files\\") + guidResult.ToString() + extension);
                lblMsg.Text = "File(s) upload successsfuly.";
            }
        }
}
4

2 回答 2

1

你能不能只break在代码中添加一条语句,如下所示:

....
if (!validExtensions.Contains(extension.ToLower()))
{
    lblMsg.Text = "Extension not supported";
    break;
}
....
于 2013-08-01T20:34:46.283 回答
0

在保存其中任何一个之前,请检查所有内容。一个例子是:

List<string> validExtensions = new List<string> { ".jpg", ".jpeg", ".png", ".stl" };

if (hcf.PostedFiles.Any(x => !validExtensions.Contains(Path.GetExtension(x.FileName))))
{
     lblMsg.Text = "Extension not supported";
     return;
}    

//rest of your code here. which by the way, looks better like this:
foreach (var item in hcf.PostedFiles)
{
   string guidResult = System.Guid.NewGuid().ToString();
   item.SaveAs(Server.MapPath("files\\") + guidResult.ToString() + extension);
}
于 2013-08-01T20:36:22.880 回答