如何上传使用ASP.net MVC4实体框架/显示图像 [英] How to upload/display images using ASP.net MVC4 with Entity Framework
问题描述
我有一个数据模型,像这样
I have a data model like so
public class NewsItem
{
public virtual int Id { get; set; }
public virtual string NewsTitle { get; set; }
public virtual string NewsContent { get; set; }
public virtual byte[] NewsImage { get; set; }
public virtual DateTime DateAdded { get; set; }
public virtual bool IsLive { get; set; }
}
我再通过像这样一个视图中显示这样的数据:
I then display this data through a View like so:
@model BusinessObject.Domain.NewsItem
<div class="row-fluid">
<h3>
@Html.ValueFor(model => model.NewsTitle)
</h3>
<div class="span5">
<img src="~/Content/images/stock.jpg" />
</div>
<div class="span7">
<p>
@Html.ValueFor(model => model.DateAdded)
</p>
<p>
@Html.ValueFor(model => model.NewsContent)
</p>
</div>
</div>
然后我在我的控制器节约使用_db.SaveChanges()中的数据,像这样:
I then save the data using the _db.SaveChanges() in my controller like so:
[Authorize]
[HttpPost]
public ActionResult Create(CreateNewsViewModel input)
{
if (ModelState.IsValid)
{
var news = new NewsItem();
news.NewsTitle = input.nTitle;
news.NewsContent = input.nContent;
news.DateAdded = input.nDateAdded;
news.IsLive = input.nIsLive;
Mydb data = new Mydb();
data.NewsItems.Add(news);
data.SaveChanges();
return View("Index", data.NewsItems);
}
else
{
return View(input);
}
}
目前我没有图片上传位。我会如何呢?在我的分贝我有一个二进制字段,并在我的对象我的数据类型是一个byte []。但我不知道我需要处理图像上载?
Currently I don't have an image upload bit. How would I go about this? In my db I have a binary field, and my data type in my object is a byte[]. But I don't know where I need to handle the Image Upload?
我是否需要返回视图的单独行动?这方面的一些三分球将是盛大的。
Do I need a seperate action that returns the view? Some pointers on this would be grand.
干杯
推荐答案
您会希望类型的文件输入字段从视图和WebImage的一个实例来处理上传的图片上传:
You'll want an input field of type file to upload from the View and an instance of the WebImage to handle the uploaded image:
查看:
<input type="file" name="image" />
控制器:
WebImage image = WebImage.GetImageFromRequest();
byte[] toPutInDb = WebImage.GetBytes();
// ... put the byte array into the database
要显示从数据库中的图像,你会想检索从数据库中的字节数组,并返回一个FileAction控制器动作。您可以通过在ByteArray的另一个实例例如WebImage从数据库中检索得到这个图像(图像检索控制器动作):
To display the images from your database, you will want a controller Action that retrieves the byte array from your database and returns a FileAction. You can get this image (for the image retrieving controller action) by instantiating another WebImage instance on the bytearray you retrieve from database:
WebImage image = new WebImage(byteArrayFromDb);
File(image.GetBytes(), "image/" + image.ImageFormat, image.FileName);
这篇关于如何上传使用ASP.net MVC4实体框架/显示图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!