0

I made registration form with image upload, the all textbox values uploaded into SQL Server except the image. I wrote the code shown below and tested it, but it doesn't store any image.

But when I remove the image and just add other values, it inserts into database without any errors.

But with image it shows an error:

'Book Record could not be saved'

Image column type is varbinary(MAX).

protected void Button1_Click(object sender, EventArgs e)
{
    string fileName = string.Empty;
    string filePath = string.Empty;

    Byte[] bytes;
    FileStream fs;

    BinaryReader br;

    SqlCommand cmd = new SqlCommand("InsertBookDetails_Sp", con);
    cmd.CommandType = CommandType.StoredProcedure;

    cmd.Parameters.AddWithValue("@book_num", TextBox1.Text.Trim());
    cmd.Parameters.AddWithValue("@BookName", TextBox2.Text.Trim());
    cmd.Parameters.AddWithValue("@Publisher", TextBox3.Text.Trim());
    cmd.Parameters.AddWithValue("@Price", TextBox4.Text.Trim());
    cmd.Parameters.AddWithValue("@Author", TextBox6.Text.Trim());

    try
    {
        if (FileUpload1.HasFile)
        {
            fileName = FileUpload1.FileName;
            filePath = Server.MapPath("pth/" + System.Guid.NewGuid() + fileName);
            FileUpload1.SaveAs(filePath);

            fs = new FileStream(filePath, FileMode.Open,FileAccess.Read);
            br = new BinaryReader(fs);
            bytes = br.ReadBytes(Convert.ToInt32(fs.Length));
            br.Close();
            fs.Close();

            cmd.Parameters.AddWithValue("@BookPic", bytes);
        }

        con.Open();
        cmd.ExecuteNonQuery();

        lblStatus.Text = "Book Record saved successfully";
        lblStatus.ForeColor = Color.Green;
    }
    catch (Exception)
    {
        lblStatus.Text = "Book Record could not be saved";
        lblStatus.ForeColor = Color.Red;
    }
    finally
    {
        con.Close();
        cmd.Dispose();

        fileName = null;
        filePath = null;
        fs = null;
        br = null;
    }
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
jassim
  • 49
  • 9

1 Answers1

1

use this code

      byte[] fileBytes=  FileUpload1.FileBytes;
      cmd.Parameters.AddWithValue("@BookPic", fileBytes);

and remove FileStream method

  • Thanks , It works . But how can i modified my code to display the image in Image button before clicking ot save button to upload into database>? becouse am newbie an i aslo try to view the image before uploading into Sql server @behroz – jassim Jul 05 '18 at 13:32
  • @jassim If you want to view the bytes to image then just convert the bytes to image System.IO.File.WriteAllBytes(filename, bytes); – Procrastinating Programmer Jul 05 '18 at 13:37
  • @Alex Thanks for your response, but am newbie in C# asp.net , can u modified my code that can be view in Image Button before uploading into Database. Thanks for your help. – jassim Jul 05 '18 at 13:45