您好我正在尝试从本地文件夹向我的数据库添加一个图像并且工作成功但是保存了路径并且not displaying
在索引页面上没有图像但在数据库上是created value path
我有这个错误:
获取http://localhost:57079/'〜/ Content / img / Asp.net.svg.png'
这是创建方法:
public ActionResult Create( Article article,HttpPostedFileBase postedFile)
{
try
{
db = new IdentityDBEntities2();
if (ModelState.IsValid)
{
if (postedFile != null)
{
article.image = Convert.ToString(postedFile.ContentLength);
postedFile.InputStream.Read(System.Text.Encoding.Unicode.GetBytes(article.image), 0, postedFile.ContentLength);
string fileName = System.IO.Path.GetFileName(postedFile.FileName);
string FilePath = "~/Content/img/" + fileName;
postedFile.SaveAs(Server.MapPath(FilePath));
}
article.UserId = System.Web.HttpContext.Current.User.Identity.GetUserId();
article.Idc = Convert.ToInt32(Request["cab"]);
db.Articles.Add(article);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(article);
}
catch(Exception e) { Response.Write(e.Message); }
return View();
}
谢谢。
图像作为字节数组保存在数据库中。所以你的电话
article.image = Convert.ToString(postedFile.ContentLength);
如果你想保存实际图像是没有意义的。你需要做这样的事情:
var ms = new MemoryStream();
image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif); //Specify format here; (image is of type System.Drawing.Image)
article.image = ms.ToArray();
您的image属性必须是byte[]
类型,底层数据库列需要是VARBINARY
。
编辑:你收到一个错误,因为image
需要是System.Drawing.Image
类型,如评论中所述。如果你不能使用它(或者不想),你需要从'HttpPostedFileBase'中提取字节数组,如下所示:
var ms = new MemoryStream();
postedFile.InputStream.CopyTo(ms);
article.image = ms.ToArray();
完成所有这些后,您可以在View上显示图像,如下所示:
public ActionResult GetImage(int id)
{
var article = db.Articles.First(i => i.Id == id);
return File(article.image, "image/png"); //Adjust content type based on image type (jpeg, gif, png, etc.)
}
`@Html.EditorFor(model => model.image, new {htmlAttributes = new { @class = "form-control" ,@type="file" } }`
至
`<img src="@Url.Action("Index", "Images", new { id = Model.Id })" />`
请注意,这不会使图像可编辑。如果您需要此功能,最好提出一个新问题,因为这个答案已经超出了原始问题的范围。