您好,我正在尝试将图像从本地文件夹添加到我的数据库中,并且工作成功,但已使用路径保存,并且not displaying
在索引页面上没有图像但created value path
在数据库中
我有此错误:
GET 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();
您的图像属性需要是 typebyte[]
并且基础数据库列需要是VARBINARY
.
编辑:您收到错误,因为image
需要符合System.Drawing.Image
评论中所述的类型。如果您不能使用它(或不想使用它),您需要从 'HttpPostedFileBase' 中提取字节数组,如下所示:
var ms = new MemoryStream();
postedFile.InputStream.CopyTo(ms);
article.image = ms.ToArray();
当你完成所有这些后,你可以像这样在你的视图上显示图像:
创建一个新动作,返回每篇文章的图像
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.) }
替换 View 上的代码,以便从该操作中获取图像。
改变
`@Html.EditorFor(model => model.image, new {htmlAttributes = new { @class = "form-control" ,@type="file" } }`
至
`<img src="@Url.Action("Index", "Images", new { id = Model.Id })" />`
请注意,这不会使图像可编辑。如果您需要此功能,您最好提出一个新问题,因为此答案已经超出了您原来的问题的范围。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句