【发布时间】:2018-09-03 16:14:29
【问题描述】:
美好的一天!
如何将默认图像从项目文件夹保存到数据库?
我想要的是,单击保存按钮后,应立即将默认图像直接保存到数据库中。是否可以使用<input type=file src="~/source_here"/> 完成?
型号
public partial class tbl_Picture
{
public string picture_id { get; set; }
public byte[] picture { get; set; }
}
查看
<input type="file" src="~/image/seal.png" name="image1" id="image1"/>
控制器
public ActionResult Views(tbl_Picture pic, HttpPostedFileBase image)
{
tbl_Picture pict = new tbl_Picture();
pict.picture = new byte[image1.ContentLength];
image1.InputStream.Read(pict.picture, 0, image1.ContentLength);
db.tbl_Picture.Add(pict);
db.SaveChanges();
return View();
}
我尝试为输入文件提供照片的默认 url,以便将照片保存到数据库中。但我得到的只是对象引用未设置为对象的实例。
请指导我。提前致谢。
【问题讨论】:
-
NullReferenceException在哪一行抛出?HttpPostedFileBase image是否包含 null 值以使image1.ContentLength抛出 NRE? -
另外
<input type="file" />没有src可以指向图片路径的属性,您想在保存之前预览上传的图片,然后使用<img>标签,如<img id="image" src="#" ... />? -
@TetsuyaYamamoto 我只想将项目文件夹中的图像保存到我的数据库中
-
HttpPostedFileBase image不应该是HttpPostedFileBase image1,因为您在 HTML 中的输入是name="image1"。我认为它们必须像任何其他 HTML 表单字段一样匹配。是的,<input标签中的“src”位是什么?这没有任何意义。 -
另外,如果你想将服务器中保存的图像推送到数据库,只需使用
ReadAllBytes和Server.MapPath将其转换为byte[],以便它可以保存为varbinaryEF 的数据SaveChanges().
标签: asp.net-mvc