ASP.NET Core MVC base64映像到IFormFile
问题描述:
我遇到了问题。我将一些图像作为base64存储在数据库中,现在我需要编辑包含此图像的此对象。该图像由用户以表格的形式上传,并将其转换为base64并存储在数据库中。现在我的问题很热,要将base64图像转换回IFormFile来显示它以编辑整个对象。ASP.NET Core MVC base64映像到IFormFile
日Thnx
答
如果你想获得一个对象/视图模型包含一个byte []/BASE64, 我搜索以小时为一个解决方案,但后来我加入额外的参数到我的视图模型
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将存储可能正在上传的新图像,如您所述。 虽然参数ByteImage是从数据库中获取旧图像。
的,你完成编辑,你可以转换IFormFile为byte [],并将其保存在数据库 我试图使用映射器,但它出了问题,这个代码工作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+用户 –