我想将图像和一些其他信息保存到我的 asp.net mc3 项目中的数据库中。我之前已经将图像保存到数据库并且它有效。我在 Controller 中的代码是这样的:
public ActionResult savetodb()
{
if (Request.Files.Count > 0 && Request.Files[0] != null)
{
HttpPostedFileBase file = Request.Files[0];
var path = Path.Combine(Server.MapPath("~/Content/Image"), file.FileName);
file.SaveAs(path);
byte[] buffer = System.IO.File.ReadAllBytes(path);
myAd.AdImage = buffer;
StoreDb.AddToAds(myAd);
StoreDb.SaveChanges();
}
return View();
}
}
现在换了表,想把Image以外的其他信息存到数据库中。现在我的代码是这样的:
public ActionResult savetodb(AdvertiseView model)
{
if (Request.Files.Count > 0 && Request.Files[0] != null)
{
HttpPostedFileBase file = Request.Files[0];
var path = Path.Combine(Server.MapPath("~/Content/Image"), file.FileName);
file.SaveAs(path);
byte[] buffer = System.IO.File.ReadAllBytes(path);
myAd.AdImage = buffer;
}
myAd.AdTitle = model.AdTitle;
myAd.AdContext = model.context;
myAd.AdScope = model.Scope;
storedb.AddToAds(myAd);
storedb.SaveChanges();
return View();
}
其他信息没有问题,就是图片无法保存。我明白了
Request.Files.Count
return 0,不知道现在该怎么办。有人可以帮我吗?多谢。
最佳答案
我会使用 View 模型。
假设您首先有一个领域模型:
public class MyDomainModel
{
public byte[] AdImage { get; set; }
public string Description { get; set; }
}
然后定义一个 View 模型:
public class MyViewModel
{
[Required]
public HttpPostedFileBase File { get; set; }
[DataType(DataType.MultilineText)]
public string Description { get; set; }
}
Controller :
public class HomeController : Controller
{
public ActionResult Index()
{
return View(new MyViewModel());
}
[HttpPost]
public ActionResult Index(MyViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
// TODO: move this mapping logic into a
// mapping layer to avoid polluting the controller
// I would recommend AutoMapper for this purpose
// http://automapper.org/
using (var stream = new MemoryStream())
{
model.File.InputStream.CopyTo(stream);
var image = stream.ToArray();
var domainModel = new MyDomainModel
{
AdImage = image,
Description = model.Description
};
// TODO: persist the domain model by passing it to a method
// on your DAL layer
}
return Content("Thanks for submitting");
}
}
一旦推荐的重构完成:
public class HomeController : Controller
{
public ActionResult Index()
{
return View(new MyViewModel());
}
[HttpPost]
public ActionResult Index(MyViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
MyDomainModel domainModel = Mapper.Map<MyViewModel, MyDomainModel>(model);
// TODO: persist the domain model by passing it to a method
// on your DAL layer
return Content("Thanks for submitting");
}
}
最后是允许用户上传文件的 View :
@using (Html.BeginForm(null, null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div>
@Html.LabelFor(x => x.Description)
@Html.EditorFor(x => x.Description)
</div>
<div>
@Html.LabelFor(x => x.File)
@Html.TextBoxFor(x => x.File, new { type = "file" })
@Html.ValidationMessageFor(x => x.File)
</div>
<button type="submit">OK</button>
}
关于database - 为什么不能以这种方式将图像保存到数据库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10970992/