Sunday, May 17, 2009

Saving Image in Database (Sql Server) using .NET

I shared and done few efforts to save image in database.

Following the the function to save image to the databse.


Database Table will look like this:

create table userphoto(
photoid int,
photo image
);



protected void btnUpload_Click(object sender, EventArgs e)
{
//string _fileExtension = VirtualPathUtility.GetExtension(UploadPhoto.PostedFile.FileName);
string _fileExtension = UploadPhoto.PostedFile.FileName.Substring(UploadPhoto.PostedFile.FileName.LastIndexOf('.'));
if (_fileExtension != ".jpg" && _fileExtension != ".gif" && _fileExtension != ".bmp" && _fileExtension != ".png")
{
ltScript.Text = "Please upload images(jpeg/gif/bmp/png) files";
return;
}

int _filesize = UploadPhoto.FileBytes.Length;
if(_filesize>200000)
{
ltScript.Text="Size exeeds the limit of 200 KB, please upload a file with size of maximum 200 KB";
return;
}

FileUpload userImage = (FileUpload)UploadPhoto;
Byte[] imgByte = null;
if (userImage.HasFile && userImage.PostedFile != null)
{
//To create a PostedFile
HttpPostedFile File = UploadPhoto.PostedFile;

//Create byte Array with file len
imgByte = new Byte[File.ContentLength];

//force the control to load data in array
File.InputStream.Read(imgByte, 0, File.ContentLength);
AddUserPhoto(ID, imgByte); // calling database method
}
ltScript.Text = "File has been uploaded...";
}

// Database Method
internal bool AddUserPhoto(string ID, Byte[] Photo)
{
string conn = "server=yourservername; database=yourdatabasename; uid=userid; pwd=yourpassword;";
SqlConnection _sqlConnection= new SqlConnection(conn);

bool _isInserted = false;
_sqlCommand = new SqlCommand();
_sqlCommand.Connection = _sqlConnection;
_sqlCommand.CommandText = "insert into phototable values(@ID, @Photo)";
_sqlCommand.CommandType = CommandType.StoredProcedure;
_sqlCommand.Parameters.Add(new SqlParameter("@ID", ID));
_sqlCommand.Parameters.Add(new SqlParameter("@Photo", Photo ));
try
{
if(_sqlCommand.Connection.State != ConnectionState.Open)
_sqlCommand.Connection.Open();

int _result = _sqlCommand.ExecuteNonQuery();
if (_result > 0)
{
_isInserted = true;
}
}
catch (SqlException ex) {
// Your Error code goes here
}
finally
{
_sqlCommand.Connection.Close();
_sqlCommand = null;
}
return _isInserted;
}

Regards,
Amit Dhiman
http://www.citymatrimonials.com

No comments:

Post a Comment