![](/img/trans.png)
[英]How to get byte[] to display as a background image for a div on a view (C#, ASP.NET, MVC)
[英]C# (Asp.net MVC 2) Display image from byte[] in View
我需要將圖片保存在asp.net mvc應用程序的日期數據庫中。 我在表MimeType(nvarchar [50])和ImageData中創建了一個字段,用於將圖片保存在byte []中。 我使用ado.net。 我將圖像保存在這樣的表中:
private DBAppl db = new DBAppl();
public void CreateNewCar(newcar Car, HttpPostedFileBase image)
{
if (image != null)
{
Car.mimetype = image.ContentType;
Car.ImageData = new byte[image.ContentLength];
image.InputStream.Read(Car.ImageData, 0, image.ContentLength);
}
db.AddTonewcars(Car);
db.SaveChanges();
}
圖片正常保存在表格中。 然后我開始在View中顯示圖像。 我在控制器中創建方法
public FileContentResult GetImage(int newcarid)
{
DBAppl db = new DBAppl();
newcar car = (from p in db.newcars
where p.newcarid == newcarid
select p).First();
return File(car.ImageData, car.mimetype.Trim());
}
在視圖中,我插入了以下代碼:
<% if (Model.ImageData == null)
{ %>
None
<% }
else
{ %>
<img src="<%= Url.Action("GetImage", "Cars", new { Model.newcarid }) %>" alt="<%: Model.description %>" /> <% } %>
但是圖片沒有加載,只有alt。 救命,我做錯了什么? 我嘗試在html頁的源代碼中使用鏈接,但讀取該圖片有錯誤。 我在mozilla“有關頁面的信息”中查看,看到該頁面有我的圖片(778 kb),但它是0px x 0px。
嘗試在返回文件之前設置標題
HttpContext.Response.AddHeader("Content-Length"("Content-Type", "image/jpeg"));
或者,但是您正在訪問標頭。
將圖片/ jpeg用於jpg文件
google其他擴展名和文件tpes。
我這樣解決了這個問題:
public FileContentResult GetImage(int newcarid)
{
DBAppl db = new DBAppl();
newcar car = (from p in db.newcars
where p.newcarid == newcarid
select p).First();
return File(car.ImageData**.ToArray()**, car.mimetype.Trim());
}
在班上:
public void CreateNewCar(newcar Car, HttpPostedFileBase image)
{
**var car = new newcar();**
if (image != null)
{
car.name = Car.name;
car.date = DateTime.Now;
car.color = Car.color;
car.picmimetype = image.ContentType;
int length = image.ContentLength;
byte[] buffer = new byte[length];
image.InputStream.Read(buffer, 0, length);
car.ImageData = buffer;
}
db.AddTonewcars(car);
db.SaveChanges();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.