0

I have uploaded an Image into database through C# application. Here is my code.

FileStream fs1 = new FileStream(toolStripLableClientSelectedImage.Text, System.IO.FileMode.Open, System.IO.FileAccess.Read);
byte[] image = new byte[fs1.Length];
fs1.Read(image, 0, Convert.ToInt32(fs1.Length));
fs1.Close();

SqlCommand cmd = con.CreateCommand();
cmd.CommandText = "INSERT INTO tblClientDetails ([clFname], [clName], [clAddress], [clCity], [clState], [clPhone1], [clPhone2], [clEmail1], [clEmail2], [clProfession], [clPhoto]) VALUES ('" + txtClFirstName.Text + "', '" + txtClLastName.Text + "', '" + txtClAddress.Text + "', '" + cmbClCity.Text + "','" + cmbClState.Text + "' ,'" + txtClPhone1.Text + "' ,'" + txtClPhone2.Text + "' ,'" + txtClMail1.Text + "' ,'" + txtClMail2.Text + "' ,'" + cmbClProfession.Text + "',  @Pic)";

try
{
   SqlParameter prm = new SqlParameter("@Pic", SqlDbType.VarBinary, image.Length, ParameterDirection.Input, false, 0, 0, null, DataRowVersion.Current, image);
   cmd.Parameters.Add(prm);

   cmd.ExecuteNonQuery();
   con.Close();
   MessageBox.Show("Data Inserted Succcessfully");
}
catch (Exception ab)
{
   //MessageBox.Show("Following Error Occured. May Be Unable To Upload Image ", ab.Message);
    MessageBox.Show(ab.Message, "Error");
    con.Close();
}

This is the code I am using for uploading Image into database.

Please tell me how to write a code for downloading image from this database/filestream.

2
Contributors
6
Replies
36
Views
1 Year
Discussion Span
Last Post by Amiet_1
1

Hi

The following is an example of reading an varbinary(max) field containing an image from an SQL Server table. You will need to adapt it to fit your purpose, but the example simply reads the image and displays the image in a picture box:

string connectionString = @"Your connection string";

using (SqlConnection connection = new SqlConnection(connectionString))
{
    connection.Open();

    //Grab a unique image based on ImageID column
    string selectStatement = "SELECT Image FROM Images WHERE ImageID=@ImageID";

    using (SqlCommand command = new SqlCommand(selectStatement, connection))
    {
        command.Parameters.AddWithValue("@ImageID", 1);

        SqlDataReader reader = command.ExecuteReader();

        if (reader.HasRows)
        {
            reader.Read();
            Byte[] imageBytes = (byte[])(reader["Image"]);

            MemoryStream stream = new MemoryStream(imageBytes);
            Image image = Image.FromStream(stream);
            pictureBox1.Image = image;
        }
    }
}

HTH

0

Thanks for your Help djjeavons. But i did coding for showing image from Database to Picturebox.. Ummm... But can you please help to write this code at SaveFileDialog please... so i can save the file from Database to the Local Hard Drive.

Edited by Amiet_1

1

Hi

Once you have the image from the stream into an Image object, you can use the Save method:

image.Save(@"Path and file name to save the image");

HTH

0

Thank you for your reply djjeavons. Hey buddy but i'm getting behind on coading.. can you please please help me how can i use SaveFileDialog so user will have flexibility to save file where ever he wants.

Can you please post a little coade, which use SaveFileDialog...

1

Have a look at the SaveFileDialog class. It contains an example of its usage. Once you have the filename and location, use it in the Save method of the image object.

0

I couldn't find any satisfactory answer. So I did my own research and came up with this solution. Check out my code.

                    sfdFrmAddClient.Filter = "JPEG Files | *.jpeg";
                    string strDownloadJpegFile = "select * from [tblAdvertisement] where [advtId] = @advtIdVar";
                    string strId = lblAdvtId.Text;
                    SqlCommand sqlCmdForJpeg = new SqlCommand(strDownloadJpegFile, con);
                    sqlCmdForJpeg.Parameters.AddWithValue("@advtIdVar", strId);
                    SqlDataAdapter objAdapter = new SqlDataAdapter(sqlCmdForJpeg);
                    DataTable objTable = new DataTable();
                    DataRow objRow;
                    objAdapter.MissingSchemaAction = MissingSchemaAction.AddWithKey;
                    SqlCommandBuilder sqlCmdBuilder = new SqlCommandBuilder(objAdapter);
                    objAdapter.Fill(objTable);
                    objRow = objTable.Rows[0];

                    byte[] objData;
                    objData = (byte[])objRow["advtJpegFile"];

                    if (sfdFrmAddClient.ShowDialog() != DialogResult.Cancel)
                    {
                        string strFileToSave = sfdFrmAddClient.FileName;
                        FileStream objFileStream = new FileStream(strFileToSave, FileMode.Create, FileAccess.Write);
                        objFileStream.Write(objData, 0, objData.Length);
                        objFileStream.Close();
                    }
                }

Edited by Amiet_1

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.