base64 图像不显示在 mvc 视图中

base64 image not display in mvc view

我想在 mvc 中显示图像图像存储在数据库中文件类型是图像我想先获取图像我正在转换字节然后我想在视图中显示我正在尝试一切但图像不显示仅显示空白矩形。

conn.Open();

using (SqlCommand cmd1 = new SqlCommand("select  isnull(ClientPic,'') as ClientPic from MembersDetail where Srno=1 and MemberShipID='" + clsCommon._MembershipID + "'", conn))
{
    cmd1.CommandType = CommandType.Text;

    SqlDataAdapter ad = new SqlDataAdapter(cmd1);
    DataTable mdt_pic = new DataTable();
    ad.Fill(mdt_pic);

    for (int i = 0; i < mdt_pic.Rows.Count; i++)
    {
        ViewBag.Pic = obj_u.ClientPic = "data:image/png;base64," + Convert.ToBase64String((byte[])mdt_pic.Rows[i]["ClientPic"]);   
    }
    conn.Close();
}

<img src="@ViewBag.Pic" alt="User" />

您不需要使用 base64。您应该将文件作为 FileContentResult

public ActionResult GetFile() // note should accept an id or something
{
    byte[] bytes = null;
    conn.Open();
    using (SqlCommand cmd1 = new SqlCommand("select  isnull(ClientPic,'') as ClientPic from MembersDetail where Srno=1 and MemberShipID='" + clsCommon._MembershipID + "'", conn))
    {
        cmd1.CommandType = CommandType.Text;

        SqlDataAdapter ad = new SqlDataAdapter(cmd1);
        DataTable mdt_pic = new DataTable();
        ad.Fill(mdt_pic);

        for (int i = 0; i < mdt_pic.Rows.Count; i++)
        {
             bytes = (byte[])mdt_pic.Rows[i]["ClientPic"];
        }
        conn.Close();

    }
    return new FileContentResult(bytes, "image/png"); // content type may be different for any file
}

然后调用src中的action:

<img src="GetFile" alt="User" />