2013-03-18 60 views
3

我在形式的图片上传:MVC 3图像没有被加载

@using (Html.BeginForm("Create", "Application", FormMethod.Post, new { enctype = "multipart/form-data" })) 
    { 
    @Html.ValidationSummary(true) 
    <fieldset> 
     <legend>Application Under Testing</legend> 

     <div class="editor-label"> 
      Image 
     </div> 
     <div class="editor-field"> 
      @if (Model.AppDetails.Image == null) 
      { 
       @:None 
      } else { 
       <img width="400" src="@Url.Action("GetImage", "Application", new { Model.AppDetails.ID })" /> 
      } 
      <div>Upload new image: <input type="file" name="Image" /></div> 
     </div> 
    </fieldset> 
    } 

此提交它,它就会使用保存到数据库:

[HttpPost] 
    public ActionResult Create(ApplicationViewModel vm, HttpPostedFileBase image) 
    { 
     if (ModelState.IsValid) 
     { 
      if (image != null) 
      { 
       vm.AppDetails.ImageMimeType = image.ContentType; 
       vm.AppDetails.Image = new byte[image.ContentLength]; 
       image.InputStream.Read(vm.AppDetails.Image, 0, image.ContentLength); 
      } 

      _repository.SaveEntity<AUT>(vm.AppDetails); 

      return RedirectToAction("Index"); 
     } 

     return View(vm); 
    } 

所以,现在我有一个行动它获取图像从数据库中显示:

public FileContentResult GetImage(Guid appID) 
    { 
     var app = _repository.AUTs.FirstOrDefault(x => x.ID.Equals(appID)); 
     if (app == null) 
     { 
      return null; 
     } 

     return File(app.Image, app.ImageMimeType); 
    } 

在我看来,我有这样的代码来显示图像:

<td> 
     @if (item.Image == null) 
     { 
      @:None 
     } else { 
      <img width="100" src="@Url.Action("GetImage", "Application", new { item.ID })" /> 
     } 
    </td> 

网页上的输出是这样的:

<img width="100" src="/Validation/Application/GetImage/bd3fdb5b-8d73-48e2-a04e-1a49a73729be"> 

这是不显示图像。编辑:我实际上检查了Chrome上的元素,并且它有2个错误(每个图像为1),指出:错误500内部服务器错误。它显示了getimage的url,是否值得使用完全合格的url?或者其他的东西?

所以我的猜测是,它要么不在数据库中保存正确的数据,要么正确地将数据读入图像格式。或者我的代码错了。

有什么想法?

---编辑---

我已经在这个运行单元测试,看看我能检索图像。测试通过了。

所以,它必须与在客户端渲染它有关,因为服务器端似乎运行良好。 Chrome显示错误为:500内部服务器错误。

+0

你调试了你的代码吗? 'GetImage'方法会发生什么?它是否找到了图像? – nemesv 2013-03-18 11:29:00

+0

这就是事情,我试图把断点在获取图像,它不会被打... – 2013-03-18 11:30:17

+0

这可能有所帮助:http://stackoverflow.com/questions/8474822/displaying-database-image-bytes- in-razor-mvc3 – 2013-03-18 11:41:50

回答

0

所以,我已经找到了答案,这个问题,并停止回调到服务器:

<img width="100" src="data:@item.ImageMimeType;base64,@(Convert.ToBase64String(item.Image))" /> 

是否有使用这个任何问题,如向后兼容性与旧的浏览器?或者有什么其他的原因,我不应该使用它?

这种方式意味着我不必再次为图像查询数据库。

0

您是否已验证该文件实际上是否正在通过?我最近有类似的情况,并最终使用Request.Files去发布文件。

+0

你可以展开这个,你是如何使用请求? – 2013-03-18 12:48:47

+0

是的图像确实到达服务器。并且图像在数据库中是非常长的十六进制数字 – 2013-03-18 12:50:02

+0

如果图像到达服务器,那么这不是您的问题。 – 2013-03-18 12:51:57