我在形式的图片上传: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内部服务器错误。
你调试了你的代码吗? 'GetImage'方法会发生什么?它是否找到了图像? – nemesv 2013-03-18 11:29:00
这就是事情,我试图把断点在获取图像,它不会被打... – 2013-03-18 11:30:17
这可能有所帮助:http://stackoverflow.com/questions/8474822/displaying-database-image-bytes- in-razor-mvc3 – 2013-03-18 11:41:50