Entity Framework Reading Blob data into html img

对着背影说爱祢 提交于 2019-12-11 15:26:07

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!