I have seen these SO answers:
but these either serve physical files directly or serve from a byte array.
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)
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>
If you want to return images as base64 string you can do it like this:
public IHttpActionResult GetImage()
{
var image = GetImageData();
var base64 = Convert.ToBase64String(image);
return Ok(base64);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With