二进制图像无法在asp.net core 2.x视图上显示

时间:2018-10-02 15:19:15

标签: asp.net-core-mvc-2.0 asp.net-core-mvc-2.1

我将图像上传到具有byte []格式的表中。我的问题是,当我在视图上检索到该图像时,该图像将不会显示。

模型

{
   public byte[] image {get; set;}
}

控制器

public async Task<IActionResult> Create(Profile profile, IFormFile image)
{
    if (ModelState.IsValid)
    {
        using (var memoryStream = new MemoryStream())
        {
            image.CopyTo(memoryStream);
            profile.image = memoryStream.ToArray();
        }

        _context.Add(image);
        await _context.SaveChangesAsync();
        return RedirectToAction(nameof(Index));
    }

    return View(image);
}

查看

<img src="@item.image" />

1 个答案:

答案 0 :(得分:0)

您不能简单地将字节数组转储为HTML图像标签的源。它必须是URI。通常,这意味着您需要执行以下操作:从数据库检索图像数据并将其作为文件返回:

[HttpGet("profileimage")]
public async Task<IActionResult> GetProfileImage(int profileId)
{
    var profile = _context.Profiles.FindAsync(profileId);
    if (profile?.image == null) return NotFound();

    return File(profile.image, "image/jpeg");
}

然后,您可以执行以下操作:

 <img src="@Url.Action("GetProfileImage", new { profileId = item.Id })" />

或者,您可以使用数据URI。但是,这将导致整个图像数据包含在HTML文档中,从而增加了文档的总下载时间并延迟了渲染。此外,数据URI必须经过Base64编码,这实际上可以将图像大小增加大约1.5倍。对于小的,简单的图像,这没什么大不了的,但是对于较大的图像,您绝对应该避免这种方法。无论如何,这样做看起来像:

<img src="data:image/jpeg;base64,@Convert.ToBase64String(item.image)" />
相关问题