2
我有一种情况,在我的MVC代码中,我将图像作为httppostedfilebase类型获取。我在我的SQL数据库中有一个相应的图像类型列。将httppostedfilebase保存为SQL中的图像
我需要知道如何将这个httppostedfilebase类型转换/保存为我的数据库中的图像。
我有一种情况,在我的MVC代码中,我将图像作为httppostedfilebase类型获取。我在我的SQL数据库中有一个相应的图像类型列。将httppostedfilebase保存为SQL中的图像
我需要知道如何将这个httppostedfilebase类型转换/保存为我的数据库中的图像。
创建一个函数来HttpPostedFileBase对象转换为文件
public byte[] ConvertToByte(HttpPostedFileBase file)
{
byte[] imageByte = null;
BinaryReader rdr = new BinaryReader(file.InputStream);
imageByte = rdr.ReadBytes((int)file.ContentLength);
return imageByte;
}
这样的代码在你的控制器
public ActionResult Create(AdminDetailsViewModel viewmodel)
{
if (ModelState.IsValid)
{
HttpPostedFileBase file = Request.Files["ImageData"];
viewmodel.Image = ConvertToByte(file);
db.YourDbContextSet.Add(viewmodel);
db.SaveChanges();
}
}
希望这将有助于