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

丹尼尔

我想显示保存到数据库中的图像,我一直在寻找教程等等,但它们并没有多大帮助。我有一个 API 控制器,它由 MVC 视图及其各自的控制器使用。在视图中有一个用于显示文本的空间和图像应该在的空间,图像作为 type 保存在数据库中varbinary,文本是一个 type 字段varchar

我创建的模型:

public class ForumContentModel
{
    //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 控制器:

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

        //get the data from the different tables with the id sending from the MVC controller
        var forumContent = db.Themes.Where(x => x.IdForo == IdPost).FirstOrDefault();            

        //Content data from the post

        forum.Content = forumContent.Content;//the text part

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

MVC控制器:

    [HttpGet]
    public IActionResult watchPost(int Id)
    {
        ForumContentModel forumModel = new ForumContentModel();

        using(var client = new HttpClient())
        {
            client.BaseAddress = new Uri("https://localhost:44325/api/Forum/");

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

            responseTask.Wait();

            var result = responseTask.Result;

            if(result.IsSuccessStatusCode)
            {
                var readTask = result.Content.ReadAsAsync<ForumContentModel>();
                readTask.Wait();

                forumModel = readTask.Result;
            }
            else
            {
                ModelState.AddModelError(string.Empty, "Server error");
            }
        }

        return View(forumModel);
    }

显示数据的视图:

       <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">

                    <!--where the image should be desplayed-->
                    <img asp-for="<!--the route or the @Http.DisplayFor to bring the image?-->" alt="" class="img-fluid">

                </div>
            </div>        
        </form>

我真的不知道该怎么做,我一直在寻找一些教程,几乎所有教程都将 img 属性的源代码放在存储图像的文件夹的名称中。

任何帮助都非常感谢。

志吕

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

模型:在我的示例中,我通过 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查询数据库,返回指定的model。

[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 更改为您的。

    [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字符串,然后设置图片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>

结果是这样的:

在此处输入图片说明

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何从 Angular 数据库中的 ASP.NET Core API 下载并保存 pdf 文件?

如何在.net Core Web API中构造数据验证?

我应该如何在.NET后端将国家/地区保存在数据库中

如何在.net core中显示图像

如何在Angular项目中显示保存在wwwroot(asp.net core)中的图像

如何在ASP.NET Core Web API中仅使用LINQ从数据库获取最新ID?

asp.net core Api - 在数据库中插入新行

maxReceivedMessageSize 如何在 Asp.net Core Api 中设置?

如何在Net Core Web API中覆盖OnAuthorization?

如何在.NET Core Web API中配置并发?

如何在 .Net Core API 中实现上传表单?

如何从 ASP.NET Core web api 调用存储在 DigitalOcean 中的 postgresql 数据库?

如何使用ASP.NET Core将图像保存到数据库中的其他文件夹?

如何从保存在数据库中的链接在 php 页面中显示图像

如果.net core 中的用户的数据库中已存在,如何从选择中删除选项

如何使用laravel 8显示保存在数据库中的图像?

如何将保存在数据库中的图像显示为 longblob?

如何在 ASP.NET Core API 中的 Swagger 中将注释显示为描述段落

如何在 Angular 中从本地 Web API (ASP.NET Core) 获取数据

如何使用AD / LDAP管理ASP.NET Core中的用户?是否将用户存储在数据库中?

如何使用ADO.NET和存储过程将复杂的C#对象保存在数据库中?

如何在.NET Core的SQL数据库中更改FirstName属性?

如何在.NET Core中创建SQLite数据库文件?

如何在 .net core 中访问数据库上下文表单视图

如何在 ASP .NET Core API 内部取消 API 请求?

如何在.Net Core中分离数据库访问

如何在 .NET Core 中调用存储在 appsettings.json 中的 API?

如何从 .NET Core api 中的 MVC 视图使用 API?

如何在不调用.Net项目中任何地方的函数的情况下将所有异常保存在数据库中?