我正在尝试使用此代码保存多个图像。但它保存所有文件,包括视频,缩略图和图像。我需要做的只是保存图像。我在这做错了什么?感谢
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 :(得分: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/"))
{
...
}
}
答案 1 :(得分: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")
{
...
}
}