如何在MVC View上显示在数据库中保存为字节的图像?

时间:2016-09-29 21:15:39

标签: c# asp.net-mvc

我使用HttpPostedFileBase将上传的图像保存到我的数据库中,如下所示:

private void Upload(HttpPostedFileBase file)
{
    if (file != null && file.ContentLength > 0)
    {
        // save the file to hard drive, we can delete it later
        var FileName = Path.GetFileName(file.FileName);
        var FilePath = Path.Combine(Server.MapPath("~/Content/Images/Uploads/"), FileName);
        file.SaveAs(FilePath);

        byte[] FileBytes;
        using (var Fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
        {
            using (var Reader = new BinaryReader(Fs))
            {
                FileBytes = Reader.ReadBytes((int)Fs.Length);
            }
        }

        OrtundEntities db = new OrtundEntities();
        ImageModel Image = new ImageModel
        {
            Data = FileBytes,
        };
        db.Images.Add(Image);
        db.SaveChanges();

        //System.IO.File.Delete(filePath);
    }
}

现在我将文件字节保存在我的数据库中。

显然我不能使用HTML <img标签来显示图像,所以我应该在这里使用哪种传送机制?我是否应该保留文件并将文件路径与(或代替)字节数组一起存储?

1 个答案:

答案 0 :(得分:0)

您可以执行以下操作

  1. byte[]转换为Base64字符串,此处为sample如何转换
  2. 使用object代码或img显示图片
  3. 您的代码应如下所示:

    var base64 = Convert.ToBase64String(bytes); // bytes is the binary  data converted to byte array
    

    然后在你看来

    <img alt="" src='@(string.Format("data:image/jpeg;base64,{0}",Model.Base64))'/>
    

    <object data='@(string.Format("data:image/png;base64,{0}",Model.Base64))'></object>
    

    希望这会对你有所帮助

相关问题