簡體   English   中英

如何從 web api .net 內核返回保存在數據庫中的圖像?

[英]How to return an image saved in a database from a web api .net core?

我的數據庫中保存了一張圖片。

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

我該怎么做?

您的返回類型似乎關閉。 您可以為圖像指定 Mime 類型,例如 JPEG 文件的"ìmage/jpeg"

我確實有類似的代碼來讀取以前上傳到 Azure blobstorage 的圖像。 除了將字節數組加載到 MemoryStream 中的方式之外,function 的整體參數看起來都一樣。

嘗試

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

反而。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM