locked
how to save and retrieve images from mysql database RRS feed

  • Question

  • User1441157511 posted

    i am having slight difficulty retrieving images from the database;

    the following lines of code explain how i uploaded to d database

    protected void process_Click(object sender, EventArgs e)
    {
    try
    {

    byte[] passport1 = new byte[FileUpload1.PostedFile.ContentLength];
    HttpPostedFile image1 = FileUpload1.PostedFile;
    image1.InputStream.Read(passport1, 0, (int)FileUpload1.PostedFile.ContentLength);
    int length1 = passport1.Length;

    MySqlCommand insert = new MySqlCommand("insert into usoft.admintable (Passport) values (@img1)", conn);

    param[0] = new MySqlParameter("@img1", MySqlDbType.Blob, length1);

    param[0].Value = image1;

    insert.Parameters.Add(param[0]);

    read = insert.ExecuteReader();
    read.Close();

    }
    catch (MySqlException mysqlex)
    {
    ClientScript.RegisterStartupScript(this.GetType(), "validation", "<script language='javascript'>alert('" + mysqlex.Message + "', \n\n '" + mysqlex.Source + "', \n\n '" + mysqlex.StackTrace + "')</script>");
    }
    catch (Exception ex)
    {
    ClientScript.RegisterStartupScript(this.GetType(), "validation", "<script language='javascript'>alert('" + ex.Message + "', \n\n '" + ex.Source + "', \n\n '" + ex.StackTrace + "')</script>");
    }

    }

    and i'm retrieving it using these lines of code

    protected void ListBox_SelectedIndexChanged(object sender, EventArgs e)
    {
    try
    {
    MySqlConnection conn = new MySqlConnection(connection);
    MySqlCommand select = new MySqlCommand("select Passport from usoft.admintable where Name = '" + name.selecteditem.ToString() + "'", conn);
    MySqlDataReader read;
    conn.Open();
    read = select.ExecuteReader();
    while (read.Read())
    {
    byte[] passportImage1 = (byte[])(read["Passport"]);
    if (ListBox.SelectedIndex.Equals(0))
    {
    if (passportImage1 == null)
    {
    adminImage.ImageUrl = null;
    }
    else
    {
    MemoryStream ms = new MemoryStream(passportImage1);
    adminImage.ImageUrl = "data:image/jpeg;base64," + Convert.ToString(passportImage1);
    }
    }
    read.Close();
    conn.Close();
    }
    catch (MySqlException mysqlex)
    {
    ClientScript.RegisterStartupScript(this.GetType(), "validation", "<script language='javascript'>alert('" + mysqlex.Message + "', \n\n '" + mysqlex.Source + "', \n\n '" + mysqlex.StackTrace + "')</script>");
    }
    catch (Exception ex)
    {
    ClientScript.RegisterStartupScript(this.GetType(), "validation", "<script language='javascript'>alert('" + ex.Message + "', \n\n '" + ex.Source + "', \n\n '" + ex.StackTrace + "')</script>");
    }
    }

    yet, the image doesn't display, instead, it displays the default error image icon. it is of the jpeg format and has a 25B size in the database. i need some assistance please

    Tuesday, February 3, 2015 7:49 PM

All replies