如何在mysql(blob)中将数据库中的图像显示到网页中的“图像”控件

时间:2018-04-10 10:36:43

标签: c# mysql asp.net web

我正在尝试建立一个测试网站,我可以在数据库中上传图像和一些文本,并在“预览”图像控件中检索图像。 我已经设法将这些元素存储为varchar和blob(MEDIUMBLOB)。(MySql)

但是我无法在图像控件中显示存储的图像。

这是代码:

MySqlConnection conn;
MySqlCommand comand;
String queryStr;
MySqlDataAdapter daa;
protected void Button1_Click(object sender, EventArgs e)
{
    HttpPostedFile postedFile = FileUpload1.PostedFile;
    string fileName = Path.GetFileName(postedFile.FileName);
    string fileExtension = Path.GetExtension(fileName);
    int fileSize = postedFile.ContentLength;
    try
    {
        if (fileExtension.ToLower()==".jpg" || fileExtension.ToLower() == ".png")
        {
            AgregarCiudad();//add city method in spanish
            Response.Write("Exito");
            MostrarImagen();//show image method also in spanish lol
        }
        else
        {
            Response.Write("Solo Imagenes .jpg o .png de 15 megabites o menos.");
        }

    }
    catch (FileNotFoundException fFileNotFound)
    {
        //log the exception the specified fFileNotFound variable has to be put in a string, label or response.
        Response.Write("Error." + fFileNotFound.Message);

    }
    catch (Exception)
    {
        Response.Write("Error");
    }
}
private void AgregarCiudad()
{
    String connString = System.Configuration.ConfigurationManager.ConnectionStrings["WebAppConnString"].ToString();
    conn = new MySqlConnection(connString);
    conn.Open();
    queryStr = "";
    queryStr = "INSERT INTO testingdb.country (Relation, Name, ImageStock)" +
        "VALUES(?Relation, ?Name, ?ImageStock)";
    comand = new MySqlCommand(queryStr, conn);
    comand.Parameters.AddWithValue("?Relation", TextBox1.Text);
    comand.Parameters.AddWithValue("?Name", TextBox2.Text);
    comand.Parameters.AddWithValue("?ImageStock", FileUpload1);

    comand.ExecuteReader();
    conn.Close();
}

正如你在这里看到的,我不知道现在还能做什么,如何使这个方法在Image控件(Image1)中显示最近存储的图像?

private void MostrarImagen()
{
    String selectQuery = "SELECT ImageStock FROM testingdb.country WHERE 
Name ='" + TextBox2.Text + "'";
    comand = new MySqlCommand(selectQuery, conn);
    MySqlDataReader reader;
    reader = comand.ExecuteReader();
    Image1.ImageUrl = selectQuery;
    conn.Close();

}

1 个答案:

答案 0 :(得分:0)

我假设您正在从数据库接收blob数据。之后尝试这样的事情:

string base64String = Convert.ToBase64String(your blob);
Image1.ImageUrl = "data:image/png;base64," + base64String;