Pages

Thursday, March 31, 2011

Upload Images into DataBase

using System.IO;

using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page

{

protected void Page_Load(object sender, EventArgs e)

{

GetImagePath(Server.MapPath(“photos”));

}

private void GetImagePath(string DirPath)

{

DirectoryInfo DirInfo = new DirectoryInfo(DirPath);

int count=1;

foreach (FileInfo fl in DirInfo.GetFiles(“*.JPG”))

{

FileStream fs = new FileStream(fl.FullName.ToString(), FileMode.Open, FileAccess.Read);

byte[] buffer = new byte[fs.Length];

fs.Read(buffer, 0, (int)fs.Length);

fs.Close();

string Name = Path.GetFileNameWithoutExtension(fl.Name.ToString());

InsertImageIntoDatabase(ref buffer, Name, count);

buffer = null;

count = count+1;

}

}

private void InsertImageIntoDatabase(ref byte[] buffer, string PhotoName, int Photoid)

{

SqlConnection Conn = new SqlConnection(“”);

SqlCommand Cmd;

Conn.Open();

Cmd = new SqlCommand(“Insert Into img values(@sno,@NAME,@blob)”,Conn);

Cmd.Parameters.Add(“@sno”, Photoid);

Cmd.Parameters.Add(“@NAME”, PhotoName);

Cmd.Parameters.Add(“@blob”, buffer);

Cmd.ExecuteNonQuery();

Page.RegisterClientScriptBlock(“msg”, “<Script>alert(‘Successfully Uploaded’)</Script>”);

}

}

No comments:

Post a Comment