2013-08-01 49 views
0

我需要将图片保存在asp.net mvc应用程序的datebase中。我在表MimeType(nvarchar [50])和ImageData中创建了一个字段,用于将图片保存在byte []中。我使用ado.net。我将图像保存在如下表格中:C#(Asp.net MVC 2)从视图中的byte []显示图像

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 %>" /> <% } %> 

但图像没有被加载,只中高音。帮助,我做错了什么?我尝试使用HTML页面的索引代码中的链接,但是读取该图片有错误。我查看了mozilla“关于页面的信息”,看到那个页面有我的图片(778 kb),但它是0px x 0px。

回答

1

,请返回文件

HttpContext.Response.AddHeader("Content-Length"("Content-Type", "image/jpeg")); 

或无论你正在访问你的头前设置头。

使用图像/ JPEG为JPG文件

谷歌的其他扩展名和文件的TPE。

0

我解决了这个问题是这样的:

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();