【问题标题】:Failed to load resource picture after create in index page索引页面创建后资源图片加载失败
【发布时间】:2019-02-28 11:47:35
【问题描述】:

您好,我正在尝试将图像从本地文件夹添加到我的数据库中,并且工作成功,但使用路径保存,并且在索引页面上是 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();
    }

谢谢。

【问题讨论】:

    标签: c# asp.net asp.net-mvc


    【解决方案1】:

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

    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();
    

    您的图像属性需要是byte[] 类型,并且基础数据库列需要是VARBINARY

    编辑:您收到错误消息,因为 image 必须是 System.Drawing.Image 类型,如 cmets 中所述。如果您不能使用(或不想),您需要从 'HttpPostedFileBase' 中提取字节数组,如下所示:

    var ms = new MemoryStream();
    postedFile.InputStream.CopyTo(ms); 
    article.image = ms.ToArray(); 
    

    当你完成所有这些后,你可以像这样在你的视图上显示图像:

    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. 替换视图上的代码,以便它从该操作中获取图像。

      改变

      `@Html.EditorFor(model => model.image, new {htmlAttributes = new { @class = "form-control" ,@type="file" } }`
      

      `<img src="@Url.Action("Index", "Images", new { id = Model.Id })" />`
      

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

    【讨论】:

    • 是的,但我在哪里得到image.Save 的价值,因为我做了你说的所有事情,但是在那条线上给了我错误谢谢
    猜你喜欢
    • 1970-01-01
    • 2011-06-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-24
    相关资源
    最近更新 更多