返回图像作为url从.net 5 web api



我想从我的控制器返回图像url。

我有一个字节数组(图像)。

,我不想返回64进制

我想返回

http://localhost:6548/image/myimage.png

我该怎么做呢?

My play ground code - not for me.

public HttpResponseMessage ImageLink()
{
var images = _context.Set<Image>();
var image = images.FirstOrDefault(x => x.Id == 1);
//return File(image.Data, "image/jpeg");
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
result.Content = new ByteArrayContent(image.Data);
result.Content.Headers.ContentType = new MediaTypeHeaderValue("image/png");
return result;
}

你可以做的是将base64转换为二进制流,然后将其保存在同一应用程序中的图像文件夹中,然后返回URL作为字符串,在这种情况下,URL将是可访问的。

控制器代码如下

using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
namespace MyNameSpace
{
public class TestController : Controller
{
private readonly IWebHostEnvironment _webHostEnvironment;
public TestController(IWebHostEnvironment webHostEnvironment)
{
_webHostEnvironment = webHostEnvironment;
}
public IActionResult ImageLink()
{
byte[] file_bytes = Convert.FromBase64String("base 64 string");
string webRootPath = _webHostEnvironment.WebRootPath;
string imagePath  = Path.Combine(webRootPath, "image/myimage.png");
System.IO.File.WriteAllBytes(imagePath, file_bytes);
return Ok("http://localhost:6548/image/myimage.png");
}
}
}

最新更新