Expertize Essentials Innovation through knowledge

15Jul/092

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
);

The following code will be written in ASPX page.
<asp:FileUpload ID="UploadPhoto" runat="server" CssClass="fileupload" />
<asp:Button ID="btnUpload" runat="server" CssClass="buttonOrangeLight" OnClick="btnUpload_Click" Text="Upload" />


The following method is the code for uploading an image which will be invoked on btnUpload click event.

protected void btnUpload_Click(object sender, EventArgs e)
{
  //Get the extension of your file to be uploaded
  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;
  // Checking file 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 in C#
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 for exception
  }
  finally
  {
    _sqlCommand.Connection.Close();
    _sqlCommand = null;
  }
  return _isInserted;
}
Comments (2) Trackbacks (0)
  1. Mozilla Firefox 3.0.11 Windows XP

    Hi,

    I need to understand this code, Can you please describe what function is doing what.

    Thanks
    Kaly

  2. Mozilla Firefox 4.0 Windows XP

    The code is performing the following task:

    1. Is script of table in which data will be stored
    2. ASPX page where you html / designing stuff will be written
    3. You code to upload the image ( converting image format to binary format)
    4. Adding data to database.

    Please let me know if you have any issue doing the same.


Leave a comment

(required)

No trackbacks yet.