实体框架将Blob数据读入html img [英] Entity Framework Reading Blob data into html img
问题描述
我试图将blob数据读入html图像对象。我想避免任何文件创建和处理(除非不可避免)。我目前的代码是:
数据表:
studentID |名字| photo
---------- + ----------- + ------------
93 | Eva | Blob data
StudentEntity.cs:
public class ShortStudent
{
public string firstname {get;组; }
public int studentid {get;组; }
public string photo {get;组; }
}
然后将这些数据发送到视图如下
ShortStudent sd = new ShortStudent();
sd.firstname =<来自db的名称>;
sd.photo = Convert.ToBase64String(Serialize(< Blob data from db>));
....
返回Json(sd,JsonRequestBehavior.AllowGet);
序列化:
private byte [] Serialize(string p)
{
var binaryFormatter = new BinaryFormatter();
var ms = new MemoryStream();
binaryFormatter.Serialize(ms,p);
返回ms.ToArray();
Javascript:
< img src =data:image / gif; base64,#= data.photo#alt =< image not found> />
如果我放入一些示例数据,它会正确显示,但不会显示来自数据库的数据(db数据在序列化和转换之后是示例数据的3倍)
我只需将图像数据读为byte [],而不是
StudentEntity.cs
公共类ShortStudent
{
公共字符串firstname {get;组; }
public int studentid {get;组; }
public byte [] photo {get;组; }
}
并更改
sd.photo = Convert.ToBase64String(Serialize(< Blob data from db>));
至
string img = Convert.ToBase64String(< Blob data from db>);
并发送至JSon
I am trying to read blob data into an html image object. I want to avoid any file creation and handling in the process (unless its unavoidable). My current code is
Data table:
studentID | firstname | photo
----------+-----------+------------
93 |Eva | Blob data
StudentEntity.cs:
public class ShortStudent
{
public string firstname { get; set; }
public int studentid { get; set; }
public string photo { get; set; }
}
This data is then sent to the view as follows
ShortStudent sd = new ShortStudent();
sd.firstname = <name from db>;
sd.photo = Convert.ToBase64String(Serialize(<Blob data from db>));
....
return Json(sd, JsonRequestBehavior.AllowGet);
Serialize:
private byte[] Serialize(string p)
{
var binaryFormatter = new BinaryFormatter();
var ms = new MemoryStream();
binaryFormatter.Serialize(ms, p);
return ms.ToArray();
}
Javascript:
<img src="data:image/gif;base64,#= data.photo #" alt="<image not found>" />
If I put in some example data it displays correctly but not the data that comes from database (db data after serializing and conversion is 3 times the example data in size)
I simply had to read image data as byte[] instead of string and it worked.
StudentEntity.cs
public class ShortStudent
{
public string firstname { get; set; }
public int studentid { get; set; }
public byte[] photo { get; set; }
}
and change
sd.photo = Convert.ToBase64String(Serialize(<Blob data from db>));
to
string img = Convert.ToBase64String(<Blob data from db>);
and send in JSon
这篇关于实体框架将Blob数据读入html img的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!