【问题标题】:ASP.NET Core MVC base64 image to IFormFileASP.NET Core MVC base64 图像到 IFormFile
【发布时间】:2017-04-11 20:17:16
【问题描述】:

我有问题。我将一些图像作为 base64 存储在 DB 中,现在我需要编辑包含此图像的对象。图片由用户以表格形式上传,我将其转换为base64 并将其存储在数据库中。现在我的问题是如何将base64 字符串转换为 IFormFile 以显示它以编辑整个对象。

谢谢

【问题讨论】:

    标签: base64 asp.net-core-mvc iformfile


    【解决方案1】:

    如果您尝试获取包含 Byte[]/base64 的对象/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是从数据库中获取旧图像。

    完成编辑后,您可以将 IFormFile 转换为 byte[] 并将其保存在数据库中 我尝试使用 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();
        }
    

    【讨论】:

    • 它适合我,在一个有 3000 多个上传图片的用户的大项目中
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-12
    相关资源
    最近更新 更多