且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用ASP.NET Core将图像保存到数据库?

更新时间:2023-02-15 14:40:30

如果您需要保存到数据库,则可能会发现它很有用.这是对的修改https://www.mikesdotnetting.com/article/259/asp-net-mvc-5-with-ef-6-working-with-files 和k7Boys的大量输入在这里MVC 6 HttpPostedFileBase?

You may find this useful if u need to save to database. This was a modification of https://www.mikesdotnetting.com/article/259/asp-net-mvc-5-with-ef-6-working-with-files and lots of input from k7Boys answer here MVC 6 HttpPostedFileBase?

<input type="file" name="Image" id="Imageinput">

博客模态类应具有Img字段;

Blog Modal Class should have Img field like;

    public int BlogId{ get; set; }
    ...
    public byte[] Img{ get; set; }

控制器;

    public async Task<IActionResult> Create([Bind("BlogId,...Img")] Blog blog t, IFormFile Image)
    if (ModelState.IsValid)
        {
            if (Image!= null)

            {
                if (Image.Length > 0)

                //Convert Image to byte and save to database

                {

                    byte[] p1 = null;
                    using (var fs1 = Image.OpenReadStream())
                    using (var ms1 = new MemoryStream())
                    {
                        fs1.CopyTo(ms1);
                        p1 = ms1.ToArray();
                    }
                    Blog.Img= p1;

                }
            }

            _context.Add(client);
            await _context.SaveChangesAsync();

            return RedirectToAction("Index");
        }

带我几个小时到达这里.现在,在查看视图中的图像时,请确保这不会很复杂.享受

Took me a couple of hours to get here. Now working on viewing the images in a view, am sure this will not be complex. Enjoy