1

I have written this code. I want to upload 2 images in asp.net C# program (image and Gif). I accept image when it's JPG format.

Would you please tell me how to do so?

I read all topic similar to my problem! please don't refer me to them!:)

public ActionResult Upload(HttpPostedFileBase image , HttpPostedFileBase Gif)
{
    Image i = Image.FromFile("image.FileName");

    if (System.Drawing.Imaging.ImageFormat.Jpeg.Equals(i.RawFormat))
    {
        string imageName = Path.GetFileName(image.FileName);
        string image_path = Server.MapPath("~/Images/" + imageName);
        image.SaveAs(image_path);

        ViewBag.image_path = image_path;
    }

    string gifName = Path.GetFileName(Gif.FileName);
    string gif_path = Server.MapPath("~/Images/" + gifName);
    Gif.SaveAs(gif_path);

    ViewBag.gif_path = gif_path;

    return View();
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
For.oi
  • 29
  • 11
  • I get 2 files. one image in JPG format and another if Gif. I dont write that section about Gif condition @marc_s – For.oi Jun 26 '16 at 08:17

1 Answers1

2

Use Path.GetExtension(); method for that purpose. like

if(Path.GetExtension(image.FileName) == ".jpg")
{
  //do your work
}

Change your code a bit like

if (image != null && Path.GetExtension(image.FileName).ToLower() == ".jpeg") 
{ 
   string imageName = Path.GetFileName(image.FileName); 
   string image_path = Path.Combine(Server.MapPath("~/Images/"), imageName); 
   image.SaveAs(image_path); 
   ViewBag.image_path = image_path; 
}
Rahul
  • 76,197
  • 13
  • 71
  • 125
  • I changed my code to this but my problem is not resolved. my files are not uploaded in image folder `if (Path.GetExtension(image.FileName) == ".jpg") { string imageName = Path.GetFileName(image.FileName); string image_path = Server.MapPath("~/Images/" + imageName); image.SaveAs(image_path); ViewBag.image_path = image_path; }`@Rahul – For.oi Jun 26 '16 at 08:07
  • See edit in answer if it helps. – Rahul Jun 26 '16 at 08:19
  • thanks! Good answer, but when I debug it "imageName" is null ! and doesn't allow program to save my file in image folder @Rahul – For.oi Jun 26 '16 at 08:36
  • post your calling code. Want to see what you are passing. – Rahul Jun 26 '16 at 08:37
  • `@using (Html.BeginForm("Upload", "Home", FormMethod.Post, new { enctype = "multipart/form-data" })){

    Name: @Html.TextBoxFor(x => x.Name)

    Image:

    Gif:

    }`
    – For.oi Jun 26 '16 at 08:39
  • thank you!!!! when I debug with Chrome it worked well! sorry ..:) – For.oi Jun 26 '16 at 08:58