且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在.NET Core API中显示保存在数据库中的图像?

更新时间:2022-01-20 16:33:40

您可以参考以下示例代码:

模型:在我的示例中,我通过AppFile将文件存储在数据库中,您可以将其更改为您的文件。

[注意]在您的示例中,模型的名称是ContentForoModel,但是在控制器中,模型的名称是ForumContentModel,请检查您的代码并使用正确的模型。

public class AppFile
{
    public int Id { get; set; }
    public string Name { get; set; }
    public byte[] Content { get; set; }
}
public class ContentForoModel
{
    //some other fields
    //theme tables
    public string Content { get; set; }
    public byte[] ContentFile { get; set; } //this has the image
    public string FileType { get; set; }//the ext type of the image
    public string FileName { get; set; }//the name of the img

}

API控制器:根据ID查询数据库,返回指定机型

[Route("api/[controller]")]
[ApiController]
public class TodoController : ControllerBase
{
    private readonly ApplicationDbContext _context;
    public TodoController(ApplicationDbContext context)
    {
        _context = context;
    }

    [HttpGet]
    [Route("watchPost/{IdPost}")]
    public IActionResult watchPost(int IdPost)
    {
        ContentForoModel forum = new ContentForoModel();//this model is used to "join" various
                                                          //models

        //get the data from the different tables with the id sending from the MVC controller
        var appfile = _context.AppFiles.Where(x => x.Id == IdPost).FirstOrDefault();

        //Content data from the post

        forum.Content = appfile.Name;//the text part

        forum.ContentFile = appfile.Content;//the image
        return Ok(forum);
    }

MVC控制器:您可以将URL更改为您的URL。

    [HttpGet]
    public async Task<IActionResult> watchPost(int Id)
    {
        ContentForoModel forumModel = new ContentForoModel();
        if (Id == 0)
            Id = 1;
        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri("https://localhost:44310/api/todo/");

            var responseTask = client.GetAsync("watchPost/" + Id);

            responseTask.Wait();

            var result = responseTask.Result;

            if (result.IsSuccessStatusCode)
            {
                var apiResponse = await result.Content.ReadAsStringAsync();
                //required using Newtonsoft.Json;
                forumModel = JsonConvert.DeserializeObject<ContentForoModel>(apiResponse);
            }
            else
            {
                ModelState.AddModelError(string.Empty, "Server error");
            }
        }

        return View(forumModel);
    }

查看页面:首先将字节数组转换为base64字符串,然后设置image src属性。

@model WebApplication6.Models.ContentForoModel
 
<div class="row">
    <div class="col-md-4">
        <form asp-action="watchPost">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <div class="row">
                <div class="form-group col-8">
                    <!--Text content-->
                    <label asp-for="Content" class="control-label h2"></label>
                    <textarea rows="4" asp-for="Content" class="form-control border-0" readonly="readonly"></textarea>
                    <span asp-validation-for="Content" class="text-danger"></span>
                </div>
                <div class="form-group col-4">
                    <label asp-for="ContentFile" class="control-label h2"></label>
                    @{
                        var base64 = Convert.ToBase64String(Model.ContentFile);
                        var Image = String.Format("data:image/gif;base64,{0}", base64);
                    }
                    <img src="@Image" alt="" class="img-fluid">
                </div>
            </div>
        </form>
    </div>
</div>

结果如下: