如何使用ASP.NET Core将图像保存到数据库? [英] How to save Images to database using ASP.NET Core?

查看:824
本文介绍了如何使用ASP.NET Core将图像保存到数据库?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用ASP.NET Core(MVC 6)EF Visual Studio创建一个小型博客.我很难找到如何将图像保存到数据库.我已经读过有关IFormfile的信息,但我不太了解如何处理,我被困住了.我对此并不陌生,希望能有所帮助.

I am working on a small blog using ASP.NET Core(MVC 6) EF Visual Studio. I have trouble finding how to save images to a database. I have read about IFormfile but I do not really understand how to go about it, I am stuck. I am new to this and would love to have a little help.

我想将图像保存到我要创建的帖子中(以相同的形式).因此,我想将其保存到postID.然后我需要能够显示图像,我该怎么做?

I want to save the image to the post I am creating(In the same form). I, therefore, want to save it to postID. Then I need to be able to display the image, how do I do that?

推荐答案

如果您需要保存到数据库,则可能会发现它很有用.这是对的修改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

这篇关于如何使用ASP.NET Core将图像保存到数据库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆