Reputation: 363
I am trying to save multiple image using this code. But instead its saving all the files including video,thumbnail and image. All i need to do is to save the images only. What am I doing wrong here? Thanks
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));
Upvotes: 0
Views: 2031
Reputation: 2587
You may also check the file extension if you know that images are always going to be from safe source
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")
{
...
}
}
Upvotes: 1
Reputation: 131219
Your code never checks the type of the image and saves all files. You can detect images by checking the ContentType field or the extension of the file, eg.
HttpFileCollection httpFileCollection = Request.Files;
for (int i = 0; i < httpFileCollection.Count; i++)
{
HttpPostedFile httpPostedFile = httpFileCollection[i];
if (httpPostedFile.ContentLength > 0
&& httpPostedFile.ContentType.StartsWith("image/"))
{
...
}
}
Upvotes: 1