如何使用 MVC 4 将图像保存到数据库 [英] How to save an image to Database using MVC 4
问题描述
所以我有一个购物车项目,我必须将图像保存到数据库而不是上传到服务器,这是我的模型
命名空间 ShoppingCart.Models{[绑定(排除 =ItemID")]公共类项目{[ScaffoldColumn(false)]公共 int ItemID { 获取;放;}[显示名称(类别")]公共 int 类别 ID { 获取;放;}[显示名称(品牌")]公共 int BrandID { 获取;放;}[必填(ErrorMessage = "需要一个名字")][字符串长度(160)]公共字符串标题{获取;放;}公共字符串 描述 { 获取;放;}[必填(ErrorMessage =需要价格")][范围(0.01, 100.00,ErrorMessage = "价格必须在 0.01 和 500.00 之间")]公共十进制价格{得到;放;}[DisplayName("专辑封面网址")][字符串长度(1024)]公共字符串 ItemArtUrl { 获取;放;}公共字节[]图片{获取;放;}公共虚拟类别类别{获取;放;}公共虚拟品牌品牌{得到;放;}公共虚拟列表订单详情 { 获取;放;}}}
所以我不确定如何使用控制器插入图像或视图来显示它们,我搜索了有关此的信息,但我真的找不到任何东西,我首先使用实体框架代码.
有两种简单的方法来处理图像——一种是简单地在控制器中返回图像本身:
[HttpGet][允许匿名]公共 ActionResult ViewImage(int id){var item = _shoppingCartRepository.GetItem(id);byte[] buffer = item.Picture;return File(buffer, "image/jpg", string.Format("{0}.jpg", id));}
视图只会引用它:
此外,您可以将其包含在 ViewModel 中:
viewModel.ImageToShow = Convert.ToBase64String(item.Picture);
并在视图中:
@Html.Raw("<img src="data:image/jpeg;base64," + viewModel.ImageToShow + ""/>");
对于数据存储,您只需使用字节数组 (varbinary(max)
) 或 blob 或任何兼容类型.
上传图片
这里,一个名为 HeaderImage
的对象是一个 EntityFramework EntityObject.控制器看起来像:
[HttpPost]公共 ActionResult UploadImages(HttpPostedFileBase[] uploadImages){如果 (uploadImages.Count() <= 1){return RedirectToAction("BrowseImages");}foreach(uploadImages 中的 var 图像){如果 (image.ContentLength > 0){byte[] imageData = null;使用 (var binaryReader = new BinaryReader(image.InputStream)){imageData = binaryReader.ReadBytes(image.ContentLength);}var headerImage = 新的 HeaderImage{图像数据 = 图像数据,ImageName = image.FileName,IsActive = 真};imageRepository.AddHeaderImage(headerImage);}}return RedirectToAction("BrowseImages");}
视图看起来像:
@using (Html.BeginForm("UploadImages", "Home", FormMethod.Post, new { enctype = "multipart/form-data" })){<div class="row"><span class="span4"><input type="file" name="uploadImages" multiple="multiple" class="input-files"/></span><span class="span2"><input type="submit" name="button" value="Upload" class="btn btn-upload"/></span>
}
So I have a project which is a Shopping Cart, I have to save images to the database instead of uploading them to the server, here is my model
namespace ShoppingCart.Models
{
[Bind(Exclude = "ItemID")]
public class Item
{
[ScaffoldColumn(false)]
public int ItemID { get; set; }
[DisplayName("Category")]
public int CategoryID { get; set; }
[DisplayName("Brand")]
public int BrandID { get; set; }
[Required(ErrorMessage = "A Name is required")]
[StringLength(160)]
public string Title { get; set; }
public string Description { get; set; }
[Required(ErrorMessage = "Price is required")]
[Range(0.01, 100.00,
ErrorMessage = "Price must be between 0.01 and 500.00")]
public decimal Price { get; set; }
[DisplayName("Album Art URL")]
[StringLength(1024)]
public string ItemArtUrl { get; set; }
public byte[] Picture { get; set; }
public virtual Category Category { get; set; }
public virtual Brand Brand { get; set; }
public virtual List<OrderDetail> OrderDetails { get; set; }
}
}
So Im unsure how to go about the controller to insert images or the view to display them, I have search for information about this but I cant really find anything, Im using entity framework code first.
There are two easy ways to do images -- one is to simply return the image itself in the controller:
[HttpGet]
[AllowAnonymous]
public ActionResult ViewImage(int id)
{
var item = _shoppingCartRepository.GetItem(id);
byte[] buffer = item.Picture;
return File(buffer, "image/jpg", string.Format("{0}.jpg", id));
}
And the view would just reference it:
<img src="Home/ViewImage/10" />
Additionally, you can include it in the ViewModel:
viewModel.ImageToShow = Convert.ToBase64String(item.Picture);
and in the view:
@Html.Raw("<img src="data:image/jpeg;base64," + viewModel.ImageToShow + "" />");
For the data-store, you would simply use a byte array (varbinary(max)
) or blob or any compatible type.
Uploading images
Here, an object called HeaderImage
is an EntityFramework EntityObject. The controller would look something like:
[HttpPost]
public ActionResult UploadImages(HttpPostedFileBase[] uploadImages)
{
if (uploadImages.Count() <= 1)
{
return RedirectToAction("BrowseImages");
}
foreach (var image in uploadImages)
{
if (image.ContentLength > 0)
{
byte[] imageData = null;
using (var binaryReader = new BinaryReader(image.InputStream))
{
imageData = binaryReader.ReadBytes(image.ContentLength);
}
var headerImage = new HeaderImage
{
ImageData = imageData,
ImageName = image.FileName,
IsActive = true
};
imageRepository.AddHeaderImage(headerImage);
}
}
return RedirectToAction("BrowseImages");
}
The View would look something like:
@using (Html.BeginForm("UploadImages", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div class="row">
<span class="span4">
<input type="file" name="uploadImages" multiple="multiple" class="input-files"/>
</span>
<span class="span2">
<input type="submit" name="button" value="Upload" class="btn btn-upload" />
</span>
</div>
}
这篇关于如何使用 MVC 4 将图像保存到数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!