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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42741170/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 08:04:20  来源:igfitidea点击:

How to save Images to database using ASP.NET Core?

databasefile-uploadasp.net-coreiformfile

提问by ErikLm

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.

我正在使用 ASP.NET Core(MVC 6) EF Visual Studio 写一个小博客。我很难找到如何将图像保存到数据库中。我已经阅读了 IFormfile,但我真的不明白如何去做,我被卡住了。我对此很陌生,希望能得到一些帮助。

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? I know there is a lot to ask, but I do not know where to turn. Feel free to send links if you have any good tips or ideas.

我想将图像保存到我正在创建的帖子中(以相同的形式)。因此,我想将其保存到 postID。然后我需要能够显示图像,我该怎么做?我知道有很多问题要问,但我不知道该向哪里求助。如果您有任何好的提示或想法,请随时发送链接。

Thanks in advance!

提前致谢!

回答by sav

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-filesand lots of input from k7Boys answer here MVC 6 HttpPostedFileBase?

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

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

Blog Modal Class should have Img field like;

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

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

Controller;

控制器;

    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

我花了几个小时才到这里。现在正在查看视图中的图像,我相信这不会很复杂。享受

回答by Jagdish Kumar

Try this its working fine

试试这个它工作正常

controller

控制器

[HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Create([Bind("Id,PostMode,Message,Image,AccountId,Created,Status")] Post post, IFormFile Image)
        {
            if (ModelState.IsValid)
            {
                using (var ms = new MemoryStream())
                {
                    Image.CopyTo(ms);
                    post.Image = ms.ToArray();
                }

                    _context.Add(post);
                await _context.SaveChangesAsync();
                return RedirectToAction(nameof(Index));
            }
            return View(post);
        }

Display Image

显示图像

@foreach (var item in Model)
        {
    <img class="img-responsive full-width" src="data:image/jpeg;base64,@Convert.ToBase64String(item.Image)" />
}

回答by Nomi Ali

You can use IFormFile to save image posted from view. Below is the sample code.

您可以使用 IFormFile 来保存从视图中发布的图像。下面是示例代码。

public class UserProfileViewModel
    {
        public string UserName { get; set; }
        public IFormFile UploadedImage { get; set; }
        public string ImageUrl { get; set; }
    }

In view simply bind it with IFormFile property like:

在视图中只需将它与 IFormFile 属性绑定,例如:

<img src="@Model.ImageUrl" alt="User Logo" asp-append-version="true" />
<input type="file" asp-for="UploadedImage" />

In your controller you just need to save file on server like:

在您的控制器中,您只需要在服务器上保存文件,例如:

var filename = ContentDispositionHeaderValue
                                    .Parse(user.UploadedImage.ContentDisposition)
                                    .FileName
                                    .Trim('"');
                    filename = Path.Combine(webRoot, "/Content/UserProfile/", $@"\{filename}");
                    if (Directory.Exists(webRoot + "/Content/UserProfile/"))
                    {
                        using (FileStream fs = System.IO.File.Create(filename))
                        {
                            user.UploadedImage.CopyTo(fs);
                            fs.Flush();
                        }
                    }
model.ImageURL = "~/Content/Brands/" + user.UploadedImage.FileName;