在Asp.Net Mvc 6中将图像转换为字节

时间:2016-03-29 12:50:19

标签: c# asp.net asp.net-mvc asp.net-mvc-4

在Asp.Net Mvc 6中,我试图将图像转换为字节以将图片添加到数据库中。我找不到使用正确编码方法的方法。有人可以帮我纠正下面的代码,错误在于编码: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;
}

//控制器

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

2 个答案:

答案 0 :(得分:4)

试试这个

private byte[] ConvertToBytes(IFormFile image)
{
   byte[] CoverImageBytes = null;
   BinaryReader reader = new BinaryReader(image.OpenReadStream());
   CoverImageBytes = reader.ReadBytes((int)image.Length);
   return CoverImageBytes;
}

答案 1 :(得分:2)

你的控制器动作将是这样的

    [HttpPost]
    public virtual ActionResult Index(HttpPostedFileBase file)
    {
    .....
    .....
    byte[] m_Bytes = ReadToEnd (file.InputStream);
    ....
    ...
    }

助手方法

public static byte[] ReadToEnd(System.IO.Stream stream)
    {
        using (var memoryStream = new MemoryStream())
        {
            stream.CopyTo(memoryStream);
            return memoryStream.ToArray();
        }
    }

如果您使用的是MVC 5

使用此

private byte[] ConvertToBytes(IFormFile file)
        {
            Stream stream= file.OpenReadStream();
            using (var memoryStream = new MemoryStream())
            {
                stream.CopyTo(memoryStream);
                return memoryStream.ToArray();
            }



        }