21

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.

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?

ΩmegaMan
  • 29,542
  • 12
  • 100
  • 122
ErikLm
  • 401
  • 1
  • 6
  • 12
  • 1
    It is not a good idea to save files to the database, your database may get huge quickly, which makes backing up and restoring problematic. – Mohammed Noureldin Dec 16 '17 at 01:18
  • @MohammedNoureldin I don't understand the argument aboutbacking up and restoring. If the files are being used in the website, it is highly likely that they are important and do need to be backed up regardless of the size of the files (and database). – shelbypereira Jan 17 '20 at 06:20
  • @shelbypereira saving files into the database will make your database huge, and will affect its performance significantly. The design of the database software is not really desinged for saving files, it is the task of the file system (AFAIK). – Mohammed Noureldin Jan 17 '20 at 06:45

3 Answers3

18

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">

Blog Modal Class should have Img field like;

    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

Muzoora Savior
  • 529
  • 5
  • 16
11

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)" />
}
Shloime Rosenblum
  • 927
  • 11
  • 26
Jagdish Kumar
  • 225
  • 1
  • 4
  • 14
2

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

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:

<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;
Nomi Ali
  • 2,165
  • 3
  • 27
  • 48