我想在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" />
答案 0 :(得分:0)
您不需要使用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中调用该动作:
<img src="GetFile" alt="User" />