SamMyat says:
protected void btnSumbit_click(object sender, EventArgs e)
{
foreach (HttpPostedFile postedFile in fileUpload1.PostedFiles)
{
string ext = System.IO.Path.GetExtension(this.fileUpload1.PostedFile.FileName);
if (ext.ToUpper().Trim() != ".JPG" && ext.ToUpper() != ".PNG" && ext.ToUpper() != ".GIF" && ext.ToUpper() != ".JPEG" && ext.ToUpper() != ".TIF")
{
Response.Write("<script Language='Javascript'> alert ('Only image file allowed')</script>");
}
else
{
string filename = Path.GetFileName(postedFile.FileName);
string contentType = postedFile.ContentType;
using (Stream fs = postedFile.InputStream)
{
for (int i = 1; i <= Request.Files.Count; i++)
{
using (BinaryReader br = new BinaryReader(fs))
{
byte[] bytes = br.ReadBytes((Int32)fs.Length);
string constr = WebConfigurationManager.ConnectionStrings["SqlDbConnection"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
string query = "insert into ImageUpload values (@File_Name, @Image_File, @File_Type)";
using (SqlCommand cmd = new SqlCommand(query))
{
cmd.Connection = con;
var name = "IMG" + "_" + System.DateTime.Now + "_" + i;
cmd.Parameters.AddWithValue("@File_Name", name);
cmd.Parameters.AddWithValue("@File_Type", contentType);
cmd.Parameters.AddWithValue("@Image_File", bytes);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
Response.Write("<script Language='Javascript'> alert ('The Image File is Save Successfullly.')</script>");
BindData();
}
}
}
}
}
}
}
replace above code with below.
protected void btnSumbit_click(object sender, EventArgs e)
{
int i = 1;
foreach (HttpPostedFile postedFile in fileUpload1.PostedFiles)
{
string ext = System.IO.Path.GetExtension(this.fileUpload1.PostedFile.FileName);
if (ext.ToUpper().Trim() != ".JPG" && ext.ToUpper() != ".PNG" && ext.ToUpper() != ".GIF" && ext.ToUpper() != ".JPEG" && ext.ToUpper() != ".TIF")
{
Response.Write("<script Language='Javascript'> alert ('Only image file allowed')</script>");
return;
}
else
{
string filename = Path.GetFileName(postedFile.FileName);
string contentType = postedFile.ContentType;
using (Stream fs = postedFile.InputStream)
{
using (BinaryReader br = new BinaryReader(fs))
{
byte[] bytes = br.ReadBytes((Int32)fs.Length);
string constr = WebConfigurationManager.ConnectionStrings["SqlDbConnection"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
string query = "insert into ImageUpload values (@File_Name, @Image_File, @File_Type)";
using (SqlCommand cmd = new SqlCommand(query))
{
cmd.Connection = con;
var name = "IMG" + "_" + System.DateTime.Now + "_" + i;
cmd.Parameters.AddWithValue("@File_Name", name);
cmd.Parameters.AddWithValue("@File_Type", contentType);
cmd.Parameters.AddWithValue("@Image_File", bytes);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
i++;
}
}
}
}
}
BindData();
}
For more details refer below articles.