首页 > 解决方案 > 如何从 web api .net 核心返回保存在数据库中的图像?

问题描述

我的数据库中保存了一张图像。

public class FileData
{
    [Key]
    public Guid Oid { get; set; }
    public int size { get; set; }
    public string FileName { get; set; }
    public byte[] Content { get; set; }
}

我想从我的 web api (.Net Core 3.1) 返回文件。我试过这段代码。图像被退回,但看起来已损坏,无法看到。

    public async Task<ActionResult> GetFileData(Guid id)
    {
        var fileData = await _context.FileData.FindAsync(id);
        if (fileData == null)
        {
            return NotFound();
        }

        MemoryStream ms = new MemoryStream(fileData.Content);
        ms.Seek(0, SeekOrigin.Begin);
        string contentType = System.Net.Mime.MediaTypeNames.Application.Octet;
        return File(ms.ToArray(), contentType, fileData.FileName);
    }

我该怎么做?

标签: databaseimageapiasp.net-coredownload

解决方案


您的返回类型似乎关闭。您可以为图像指定 Mime 类型,例如"ìmage/jpeg"JPEG 文件。

我确实有一个类似的代码来读取以前上传到 Azure blobstorage 的图像。除了将字节数组加载到 MemoryStream 中的方式之外,函数的整体参数看起来是一样的。

尝试

return File(ms, "image/jpeg");

反而。


推荐阅读