我正在编写 Steven Sanderson 的书 (Pro ASP.NET MVC 3)。我在p。 294. 我已经逐字复制了书中的内容,但不起作用。
这是操作方法
public ActionResult Edit(Product product, HttpPostedFileBase image)
{
if(ModelState.IsValid)
{
if(image != null)
{
product.ImageMimeType = image.ContentType;
product.ImageData = new byte[image.ContentLength];
image.InputStream.Read(product.ImageData, 0, image.ContentLength);
}
//...Save product in the database using Entity Framework
}
}
这是如何在 Razor 页面上显示图像
<img width="150" height="150"
src = "@Url.Action("GetImage", "Home", new { Model.ProductID })" />
最后,GetImage
public FileContentResult GetImage(int productID)
{
Product prod = repository.Products.FirstOrDefault(p => p.ProductID == productID);
if (prod != null)
{
return File(prod.ImageData, prod.ImageMimeType);
}
else
{
return null;
}
}
编辑
我从头到尾跟踪了整个过程(在调试时),这就是我可以说的:
按下 View 上的“保存”按钮后,HttpPostedFileBase 对象不为空。
调用 db.SaveChanges() 方法后,数据库表中添加了一行。
当我调用 GetImage 时,它不会返回 null。
但是在 View 上,没有显示图像
感谢您的帮助
最佳答案
File
应该是 FileContentResult
因为它是字节而不是磁盘上的实际文件。 img
应该是 prod
,对吗?
public FileContentResult GetImage(int productID)
{
Product prod = repository.Products.FirstOrDefault(p => p.ProductID == productID);
if (prod != null)
{
return new FileContentResult(prod.ImageData, prod.ImageMimeType);
}
else
{
return null;
}
}
关于asp.net-mvc-3 - ASP.NET MVC3 : upload image and save it to database,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7260638/