我是MVC的初学者,我正在尝试将图像添加到数据库,然后在前端检索它.
我添加了我的课程:
using System;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Web.Mvc;
namespace TestProject.Data
{
public partial class UpcomingEvent
{
public UpcomingEvent()
{
EventDate = DateTime.Now;
DateTimeStamp = DateTime.Now;
Cancelled = false;
}
[Key]
public int EventID { get; set; }
public DateTime EventDate { get; set; }
public string Title { get; set; }
public string Blurb { get; set; }
public string Body { get; set; }
public byte[] EventImage { get; set; }
public DateTime DateTimeStamp { get; set; }
public bool Cancelled { get; set; }
}
}
然后使用Entity Framework创建一个具有读/写操作的控制器.在创建/编辑等中,除图像之外的所有字段都显示.
为了将图像发送到每个条目的数据库,我需要添加到控制器或视图中?
最佳答案 以下是我们保险代理机构的一个工作示例.我将徽标存储在目录中.我也在调整徽标大小,并使用ImageResizer创建移动版本(可以使用Package Manager安装).虽然这没有必要,但它是一个很好的工具,特别是在接受最终用户的上传时.
视图:
@using (Html.BeginForm("Upload","LogoController", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div class="form-horizontal">
<div class="control-group">
<label>
Upload A Logo</label>
<div class="controls">
<input type="file" name="logo" />
</div>
</div>
</div>
<p><input type="submit" name="Upload" value="Upload" class="button" />
</p>
}
控制器:
[HttpPost]
public ActionResult Upload(HttpPostedFileBase logo)
{
SaveLogos(logo);
return View();
}
private void SaveLogos(HttpPostedFileBase logo)
{
if (logo != null && logo.ContentLength > 0)
{
var ext = Path.GetExtension(logo.FileName);
var path = Server.MapPath("~/Content/Images");
var full = Path.Combine(path, "logo.png");
path = Path.Combine(path, "Mobile");
var mobile = Path.Combine(path, "logo.png");
var tmp = Path.GetTempFileName() + "." + ext;
try
{
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
if (System.IO.File.Exists(full))
{
System.IO.File.Move(full, full.Replace(".png", DateTime.Now.ToString("yyyyMMdd_hhmmss") + ".png"));
}
if (System.IO.File.Exists(mobile))
{
System.IO.File.Move(mobile, mobile.Replace(".png", DateTime.Now.ToString("yyyyMMdd_hhmmss") + ".png"));
}
// convert to png
logo.SaveAs(tmp);
var job = new ImageResizer.ImageJob(tmp, full,
new ImageResizer.ResizeSettings("width=460;height=102;format=png;mode=pad"));
job.Build();
// create mobile image
job = new ImageResizer.ImageJob(tmp, mobile,
new ImageResizer.ResizeSettings("width=190;height=44;format=png;mode=pad"));
job.Build();
}
catch (Exception e)
{
Logging.LogError(e, ControllerContext);
}
finally
{
System.IO.File.Delete(tmp);
}
}
}
将其存储到EF中将需要获取图像的字节,可能对它们进行编码(可能是base64),然后将结果存储到对象中.该CodeProject Article提供了将文件存储到varbinary(MAX)字段的示例.
最后,如果我没有提供关于在您的数据库中存储图像的警告,我会疏忽.如果图像大于1MB,Microsoft建议不要这样做.有关类似的讨论,请参见Entity Framework Column Type for Base64 String.