Database 将varbinary转换为img并在mvc4中显示图像
我为在数据库中保存图像编写以下代码:Database 将varbinary转换为img并在mvc4中显示图像,database,asp.net-mvc-4,varbinary,Database,Asp.net Mvc 4,Varbinary,我为在数据库中保存图像编写以下代码: public ActionResult Create(Slider slider) { if (ModelState.IsValid) { int Len = Request.Files[0].ContentLength; byte[] fileBytes = new byte[Len]; Request.Files[0].InputStream.
public ActionResult Create(Slider slider)
{
if (ModelState.IsValid)
{
int Len = Request.Files[0].ContentLength;
byte[] fileBytes = new byte[Len];
Request.Files[0].InputStream.Read(fileBytes, 0, Len);
slider.SliderImage = fileBytes;
db.Slider.Add(slider);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(slider);
}
如何将varbinary更改为image以显示数据?据我所知,为了在asp.net mvc中显示图像,以下代码将起作用:-
public ActionResult DownloadFile(int fileId)
{
SliderEntities db = new SliderEntities ();
var content = db.Slider.Where(m => m.ID == fileId).FirstOrDefault();
byte[] contents = (byte[])content.SliderImage; //here varbinary to byte conversion will take place.
return File(contents, "image/jpg"); //here instead of 'jpg' you can return any image format.
}
将字节数组转换为base64字符串,并按如下方式显示 将字节数组转换为基64字符串的代码
public static string ToBase64ImageString(this byte[] data)
{
return string.Format("data:image/jpeg;base64,{0}", Convert.ToBase64String(data));
}
要将其显示为图像,可以使用以下代码
<img src='@Model.SliderImage.ToBase64ImageString()' />
不要忘记在您的视图中使用扩展方法的名称空间。请选择一个。我认为下面的答案将对您有所帮助。。如果需要更多,请发表评论。。。