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

c3frrgcw  于 2021-06-24  发布在  Mysql
关注(0)|答案(1)|浏览(466)

我正在尝试做一个测试网站,在那里我可以上传一个图像和一些数据库中的文本,并检索“预览”图像控件中的图像。我已经设法将这些元素存储为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();
}

正如您在这里看到的,我不知道现在还需要做什么,可以做些什么使这个方法在图像控件(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();

}
aiazj4mn

aiazj4mn1#

我假设您正在从数据库接收blob数据。在那之后,试着这样做:

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

相关问题