0

我正在尝试使用此代码保存多个图像。但相反,它保存了所有文件,包括视频、缩略图和图像。我需要做的就是只保存图像。我在这里做错了什么?谢谢

    List<string> img = new List<string>();
                HttpFileCollection httpFileCollection = Request.Files;
                for (int i = 0; i < httpFileCollection.Count; i++)
                {
                    HttpPostedFile httpPostedFile = httpFileCollection[i];
                    if (httpPostedFile.ContentLength > 0  && httpPostedFile.ContentType.StartsWith("image/"))
                    {
                        httpPostedFile.SaveAs(Server.MapPath("~/Icon/") + System.IO.Path.GetFileName(httpPostedFile.FileName));
                        img.Add(Server.MapPath("~/Icon/") + System.IO.Path.GetFileName(httpPostedFile.FileName));
                    }
                    
                }

cmd.Parameters.AddWithValue("@ImageURL", img.ToArray().Length > 0 ? String.Join(",", img.ToArray()) : Path.GetFileName(FileUpload2.PostedFile.FileName));
4

2 回答 2

1

您的代码从不检查图像的类型并保存所有文件。您可以通过检查 ContentType 字段或文件的扩展名来检测图像,例如。

HttpFileCollection httpFileCollection = Request.Files;
for (int i = 0; i < httpFileCollection.Count; i++)
{
    HttpPostedFile httpPostedFile = httpFileCollection[i];
    if (httpPostedFile.ContentLength > 0 
       && httpPostedFile.ContentType.StartsWith("image/"))
    {
         ...
    }
}
于 2012-06-20T10:03:20.530 回答
1

如果您知道图像总是来自安全来源,您也可以检查文件扩展名

HttpFileCollection httpFileCollection = Request.Files;
for (int i = 0; i < httpFileCollection.Count; i++)
{
    HttpPostedFile httpPostedFile = httpFileCollection[i];
    string fileNameExtension = System.IO.Path.GetExtension(httpPostedFile.FileName);
    if (httpPostedFile.ContentLength > 0 &&  fileNameExtension ==".Jpg")
    {
         ...
    }
}
于 2012-06-20T10:10:33.387 回答