问题
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)
回答1:
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
来源:https://stackoverflow.com/questions/46821094/entity-framework-reading-blob-data-into-html-img