【问题标题】:base64 image not display in mvc viewbase64 图像不显示在 mvc 视图中
【发布时间】:2018-03-06 13:35:13
【问题描述】:

我想在 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" />

【问题讨论】:

    标签: c# asp.net-mvc-4 model-view-controller ado.net


    【解决方案1】:

    您不需要使用 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" />
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-25
      • 2013-01-31
      相关资源
      最近更新 更多