直接从Web API核心端点返回base64编码的图像 [英] return base64 encoded images directly from a web api core endpoint

查看:182
本文介绍了直接从Web API核心端点返回base64编码的图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到了这些答案:

I have seen these SO answers:

  • Return an image from asp.net web api core as IActionResult
  • Response.Body.WriteAsync base64 string not working

但是这些要么直接提供物理文件,要么从字节数组提供.

but these either serve physical files directly or serve from a byte array.

请为我们的Web API端点提供一种直接从data:image/png; base64,(我们的base64字符串)返回内容类型:image/png

Please is there a way for our Web API Endpoint to return content-type: image/png directly from data:image/png;base64,(our base64 string)

推荐答案

从文件夹中读取文件非常简单.诀窍是使用 ASP.NET Core 中的 IHostingEnvironment 来获取当前的Web根路径.

It is quite straight forward to read a file from a folder. The trick is to use IHostingEnvironment in ASP.NET Core to get the current web root path.

using System;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;

namespace DemoWebApiCore.Controllers
{
    [Route("api/[controller]")]
    public class FilesController : Controller
    {
        private readonly IHostingEnvironment _hostingEnvironment;

        public FilesController(IHostingEnvironment hostingEnvironment)
        {
            _hostingEnvironment = hostingEnvironment;
        }

        // GET api/files/sample.png
        [HttpGet("{fileName}")]
        public string Get(string fileName)
        {
            string path = _hostingEnvironment.WebRootPath + "/images/" + fileName;
            byte[] b = System.IO.File.ReadAllBytes(path);
            return "data:image/png;base64," + Convert.ToBase64String(b);
        }
    }
}

用法

HomeController.cs

using Microsoft.AspNetCore.Mvc;

namespace DemoWebApiCore.Controllers
{
    public class HomeController : Controller
    {
        // GET: /<controller>/
        public IActionResult Index()
        {
            return View();
        }
    }
}

Index.cshtml

<html>
<body>
    <img id="sample-img" />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <script type="text/javascript">
        $(function () {
            var url = "/api/files/sample.png";
            $.get(url, function (data) {
                console.log(data);
                $("#sample-img").attr('src', data);
            });
        })
    </script>
</body>
</html>

这篇关于直接从Web API核心端点返回base64编码的图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆