[英]Convert image To Bytes in Asp.Net Mvc 6
In Asp.Net Mvc 6, I am trying to convert image to bytes for adding the picture into database.在 Asp.Net Mvc 6 中,我试图将图像转换为字节以将图片添加到数据库中。 I cannot find the way to use the right method of encoding.我找不到使用正确编码方法的方法。 Can someone help me to correct this below code, the mistake is at encoding: UInt32 which is not valid in the given context.有人可以帮我更正下面的代码吗,错误在于编码:UInt32 在给定的上下文中无效。
private readonly ApplicationDbContext _context = new ApplicationDbContext();
public int UploadImageInDataBase(IFormFile file, PublisherInfos publisherInfos)
{
publisherInfos.CoverImage = ConvertToBytes(file);
var pubInfos = new PublisherInfos
{
ImageSize = publisherInfos.ImageSize,
FileName = publisherInfos.FileName,
CoverImage = publisherInfos.CoverImage
};
_context.PublisherInfos.Add(pubInfos);
int i = _context.SaveChanges();
if (i == 1)
{
return 1;
}
else
{
return 0;
}
}
// ConvertToBytes // 转换为字节
private byte[] ConvertToBytes(IFormFile image)
{
byte[] CoverImageBytes = null;
var _reader = new StreamReader(image.OpenReadStream());
BinaryReader reader = new BinaryReader(_reader.ReadToEndAsync, encoding: UInt32);
CoverImageBytes = reader.ReadBytes((int)image.Length);
return CoverImageBytes;
}
// Controller // 控制器
public IActionResult Create(PublisherInfos publisherInfos)
{
if (ModelState.IsValid)
{
IFormFile file = Request.Form.Files["CoverImage"];
PublisherInfosRepository service = new PublisherInfosRepository();
int i = service.UploadImageInDataBase(file, publisherInfos);
if (i == 1)
{
// Add file size and file name into Database
_context.PublisherInfos.Add(publisherInfos);
_context.SaveChanges();
return RedirectToAction("Index", new { Message = PublisherInfoMessageId.DataloadSuccess });
}
}
return View(publisherInfos);
}
try this尝试这个
private byte[] ConvertToBytes(IFormFile image)
{
byte[] CoverImageBytes = null;
BinaryReader reader = new BinaryReader(image.OpenReadStream());
CoverImageBytes = reader.ReadBytes((int)image.Length);
return CoverImageBytes;
}
You Controller Action will be like this你的控制器动作会是这样的
[HttpPost]
public virtual ActionResult Index(HttpPostedFileBase file)
{
.....
.....
byte[] m_Bytes = ReadToEnd (file.InputStream);
....
...
}
The Helper Method辅助方法
public static byte[] ReadToEnd(System.IO.Stream stream)
{
using (var memoryStream = new MemoryStream())
{
stream.CopyTo(memoryStream);
return memoryStream.ToArray();
}
}
If you are using MVC 5如果您使用的是 MVC 5
use this用这个
private byte[] ConvertToBytes(IFormFile file)
{
Stream stream= file.OpenReadStream();
using (var memoryStream = new MemoryStream())
{
stream.CopyTo(memoryStream);
return memoryStream.ToArray();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.