Dren Ibrahimi
Dren Ibrahimi

Reputation: 27

Uploading image to database in .NET 6

I'm building an app in .NET 6 and React. I'm working on a feature to add images to the database.

So far, when uploading an image, it gets added to my desired folder with a specific name. However, when checking the users I can see that the imageFile column is null.

enter image description here

My client model file looks like this:

namespace NDereAPI.Models
{
    public partial class Klienti
    {
        public Klienti()
        {
            MyCarts = new HashSet<MyCart>();
        }

        public int KlientiId { get; set; }
        public string Name { get; set; } = null!;
        public string Surname { get; set; } = null!;
        public string Email { get; set; } = null!;
        public string Password { get; set; } = null!;
        public string PhoneNumber { get; set; } = null!;
        public string StreetName { get; set; } = null!;
        public string ZipCode { get; set; } = null!;
        public string City { get; set; } = null!;
        public string Role { get; set; } = null!;
        public string Picture { get; set; }

        [NotMapped]
        public IFormFile ImageFile { get; set; }

        public virtual ICollection<MyCart> MyCarts { get; set; }
    }
}

And my methods in the ClientController look like this:

[NonAction]
public async Task<string> SaveImage(IFormFile imageFile)
{
    string imageName = new String(Path.GetFileNameWithoutExtension(imageFile.FileName)
            .Take(10).ToArray()).Replace(' ', '-');
    imageName = imageName + DateTime.Now.ToString("yymmssfff") + Path.GetExtension(imageFile.FileName);

    var imagePath = Path.Combine(_hostEnvironment.ContentRootPath, "Images", imageName);

    using (var fileStream = new FileStream(imagePath, FileMode.Create))
    {
        await imageFile.CopyToAsync(fileStream);
    }

    return imageName;
}

[HttpPost]
public async Task<ActionResult<List<Klienti>>> AddClient([FromForm] Klienti klient)
{
    klient.Picture = await SaveImage(klient.ImageFile);
    dataContext.Klientet.Add(klient);
    await dataContext.SaveChangesAsync();

    return Ok(await dataContext.Klientet.ToListAsync());
}

Note: the Picture column is just the name of the saved image.

What am I doing wrong? Let me know if I should provide more info about this problem.

Also, I would love a recommendation on a tutorial about storing images in the database for .NET 6 and React. I haven't stumbled upon the perfect source yet...

Upvotes: 1

Views: 975

Answers (2)

Vikash Agrawal
Vikash Agrawal

Reputation: 119

You will need to convert your file to a encoded byte array and then to string to save it. See this SO post Convert posted file to byte array

The not mapped file field can be a string or may be byte array and must be given value by programming the way image path is added to picture field.

Upvotes: -1

SmartCoder
SmartCoder

Reputation: 1032

In your code, ImageFile is [NotMapped] in class Klienti. The [NotMapped] attribute is used to specify that an entity or property is not to be mapped to a table or column in the database. That's why Entity Framework is ignoring this and not storing in Database.

Upvotes: 2

Related Questions