Wednesday, March 3, 2010

Web Application : How to upload multiple images at a time

//First add image control into the web form how many you want to upload images at a time
//Add one button
//Write the below code into the button_click event

if (FileUpload1.HasFile)
{
string imagefile = FileUpload1.FileName;

if (CheckFileType(imagefile) == true)
{
Random rndob = new Random();
int db = rndob.Next(1, 100);
filename = System.IO.Path.GetFileNameWithoutExtension(imagefile) + db.ToString() + System.IO.Path.GetExtension(imagefile);

String FilePath = "images/" + filename;
FileUpload1.SaveAs(Server.MapPath(FilePath));

objimg.ImageName = filename;
Image1();

if (Session["imagecount"].ToString() == "1")
{
Img1.ImageUrl = FilePath;
ViewState["img1"] = FilePath;
}
else if (Session["imagecount"].ToString() == "2")
{
Img1.ImageUrl = ViewState["img1"].ToString();
Img2.ImageUrl = FilePath;
ViewState["img2"] = FilePath;
}
else if (Session["imagecount"].ToString() == "3")
{
Img1.ImageUrl = ViewState["img1"].ToString();
Img2.ImageUrl = ViewState["img2"].ToString();
Img3.ImageUrl = FilePath;
ViewState["img3"] = FilePath;
}
else if (Session["imagecount"].ToString() == "4")
{
Img1.ImageUrl = ViewState["img1"].ToString();
Img2.ImageUrl = ViewState["img2"].ToString();
Img3.ImageUrl = ViewState["img3"].ToString();
Img4.ImageUrl = FilePath;
ViewState["img4"] = FilePath;
}
else if (Session["imagecount"].ToString() == "5")
{
Img1.ImageUrl = ViewState["img1"].ToString();
Img2.ImageUrl = ViewState["img2"].ToString();
Img3.ImageUrl = ViewState["img3"].ToString();
Img4.ImageUrl = ViewState["img4"].ToString();
Img5.ImageUrl = FilePath;
ViewState["img5"] = FilePath;
}

}


}
//execption handling
else
{
lblErrMsg.Visible = true;
lblErrMsg.Text = "";
lblErrMsg.Text = "please select a file";
}

}

//if file extension belongs to these list then only allowed
public bool CheckFileType(string filename)
{
string ext;
ext = System.IO.Path.GetExtension(filename);
switch (ext.ToLower())
{
case ".gif":
return true;
case ".jpeg":
return true;
case ".jpg":
return true;
case ".bmp":
return true;
case ".png":
return true;
default:
return false;
}
}

No comments: