0

我将图像上传到具有 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" />
4

1 回答 1

1

您不能简单地将字节数组转储为 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)" />
于 2018-10-02T17:43:10.197 回答