ASP.NET Core MVC base64 image for IFormFile

I have a problem. I saved some images in the database as base64, and now I need to edit this object that contains this image. The image is uploaded by the user in the form, and I converted it to base64and saved it to the database. Now my problem is how to convert the string base64to IFormFile in order to display it for editing the whole object.

thank

+5
source share
1 answer

If you are trying to get a / viewModel object containing [] / base64 bytes, I searched in the clock for a solution, but then added an extra parameter to my view model

    public class ProductAddVM
{
    public int Id { get; set; }
    public Categories Category { get; set; }
    public decimal Vat { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
    public IFormFile Image { get; set; }
    public Byte[] ByteImage { get; set; }
    public string Description { get; set; }
    public bool? Available { get; set; }
}

Image - , EDIT, . ByteImage .

, IFormFile [] DataBase Mapper, , 100%, .

        internal ProductAddVM GetProduct(int id)
    {
        var model = new Product();
        model = Product.FirstOrDefault(p => p.Id == id);
        var viewModel = new ProductAddVM();
        viewModel.Id = model.Id;
        viewModel.Name = model.Name;
        viewModel.Available = model.Available;
        viewModel.Description = model.Description;
        viewModel.Price = model.Price;
        viewModel.Category = (Categories)model.Category;
        viewModel.Vat = model.Vat;
        viewModel.ByteImage = model.Image;
        return viewModel;
    }


    internal void EditProduct(int id, ProductAddVM viewModel,int userId)
    {
        var tempProduct = Product.FirstOrDefault(p => p.Id == id);
        tempProduct.Name = viewModel.Name;
        tempProduct.Available = viewModel.Available;
        tempProduct.Description = viewModel.Description;
        tempProduct.Price = viewModel.Price;
        tempProduct.Category =(int)viewModel.Category;
        tempProduct.Vat = CalculateVat(viewModel.Price,(int)viewModel.Category);
        if (viewModel.Image != null)
        {
            using (var memoryStream = new MemoryStream())
            {
                viewModel.Image.CopyToAsync(memoryStream);
                tempProduct.Image = memoryStream.ToArray();
            }
        }
        tempProduct.UserId = userId;
        tempProduct.User = User.FirstOrDefault(u => u.Id == userId);

        SaveChanges();
    }
-1

Source: https://habr.com/ru/post/1674602/


All Articles