加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

ASP.NET Core MVC base64映像到IFormFile

发布时间:2020-12-16 07:38:45 所属栏目:asp.Net 来源:网络整理
导读:我有个问题.我将一些图像存储在DB中作为base64,现在我需要编辑包含此图像的此对象.用户在表单中上传图像,然后将其转换为base64并将其存储在DB中.现在我的问题很热,将base64图像转换回IFormFile以显示它以编辑整个对象. 日Thnx 解决方法 If you’re trying to
我有个问题.我将一些图像存储在DB中作为base64,现在我需要编辑包含此图像的此对象.用户在表单中上传图像,然后将其转换为base64并将其存储在DB中.现在我的问题很热,将base64图像转换回IFormFile以显示它以编辑整个对象.

日Thnx

解决方法

If you’re trying to get a object/viewModel that contains a Byte[]/base64,
i searched in hours for a solution but then i added extra parameter to my viewmodel

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是从数据库中获取旧图像.

The where you’re done editing you can convert the IFormFile to byte[] and save it in DataBase
I tried to use Mapper but it went wrong,this code is working 100% but i’m gonna make it look better

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();
    }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读