我有一种情况,我在我的 MVC 代码中获取了一个 httppostedfilebase 类型的图像。我的 SQL 数据库中有一个相应的图像类型列。
我需要知道如何在我的数据库中将此 httppostedfilebase 类型转换/保存为图像。
我有一种情况,我在我的 MVC 代码中获取了一个 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();
}
}
希望这会有所帮助