2012-06-20 114 views
0

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

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)); 
+0

你永远不检查文件是否是一个图像。您为所有文件调用httpPostedFile.SaveAs –

+0

尝试在'if(httpPostedFile.ContentLength> 0)'中添加另一个语句,该语句将检查文件是否为图像 – harry180

+0

我已根据建议和帮助编辑了代码。但现在的问题是,数据不会被同一行中的逗号分隔。而是将每个图像路径保存在一个新行中。我怎样才能解决这个问题?谢谢。 –

回答

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/")) 
    { 
     ... 
    } 
} 
+0

我的意思是,现在图像即将到来,但它们不会被逗号隔开,而是每个新图像都会出现在新的一行中。查看我现在使用的更新代码。谢谢。 –

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") 
    { 
     ... 
    } 
}