在索引页面中创建后无法加载资源图片

问题描述 投票:0回答:1

您好我正在尝试从本地文件夹向我的数据库添加一个图像并且工作成功但是保存了路径并且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();
    }

谢谢。

c# asp.net asp.net-mvc
1个回答
0
投票

图像作为字节数组保存在数据库中。所以你的电话

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上显示图像,如下所示:

  1. 创建一个返回每篇文章图像的新操作 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.) }
  2. 替换View上的代码,以便从该操作中获取图像。 更改 `@Html.EditorFor(model => model.image, new {htmlAttributes = new { @class = "form-control" ,@type="file" } }` `<img src="@Url.Action("Index", "Images", new { id = Model.Id })" />`

请注意,这不会使图像可编辑。如果您需要此功能,最好提出一个新问题,因为这个答案已经超出了原始问题的范围。

© www.soinside.com 2019 - 2024. All rights reserved.