【问题标题】:Return Image as url from .net 5 web api [closed]从.net 5 web api返回图像作为url [关闭]
【发布时间】:2021-07-26 16:23:33
【问题描述】:

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

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

我不想以 64 为基数返回。

我想退货

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

我该怎么做?

我的游乐场代码 - 对我不起作用。

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;
        }

【问题讨论】:

  • 我不清楚你的意思。你只想返回一个字符串?谷歌搜索finds examples of that。但是您的字符串是有效的 URL 吗?您如何确定该 URL?显示的代码似乎与此无关,而是返回二进制文件数据。你能澄清一下你到底想要完成什么以及为什么?

标签: c# webapi


【解决方案1】:

您可以做的是将 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");
        }

    }
}

【讨论】:

  • @Yana T 这是你的问题的答案吗?
  • 字符串 webRootPath = _webHostEnvironment.WebRootPath;为空
  • 我正在使用 web api,我没有 wwwroot
猜你喜欢
  • 2015-08-05
  • 1970-01-01
  • 2021-07-06
  • 2017-09-11
  • 1970-01-01
  • 1970-01-01
  • 2016-05-02
  • 2016-04-23
  • 1970-01-01
相关资源
最近更新 更多