【问题标题】:Returning an image using Web API使用 Web API 返回图像
【发布时间】:2019-03-16 15:37:45
【问题描述】:

我有一个 Web 服务方法,如下所示:

[HttpGet("{id}")]
public ActionResult<byte[]> Get(Guid id)
{
    var files = Directory.GetFiles(@"Pictures\");
    foreach (var file in files)
    {
        if (file.Contains(id.ToString()))
        {
            return System.IO.File.ReadAllBytes(file);
        }
    }
    return null;
}

这是客户端代码,它肯定在工作,即它正在调用 Web 服务并且 Web 服务正在返回图像:

var response2 = await client.GetAsync("http://localhost:59999/api/Images/5c60f693-bef5-e011-a485-80ee7300c692");
byte[] image2 = await response2.Content.ReadAsByteArrayAsync(); //https://stackoverflow.com/questions/39190018/how-to-get-object-using-httpclient-with-response-ok-in-web-api
System.IO.File.WriteAllBytes("image.jpg", image2);

当我尝试在 Paint 中打开 image.jpg 时;它说这是一个无效文件。有什么问题?

【问题讨论】:

  • webervice截取的图片,你确定这是jpg吗?
  • @D.J,我很确定。我刚刚检查过。
  • 好的,你能检查一下客户端收到的bytearray是否和webservice发送的一样长吗?可能图像没有完全发送给客户端
  • @D.J,字节数组的大小不同。有问题。如何从响应中获取图像?我无法相信这是多么困难。
  • 我的第一个猜测是客户端没有收到图像,而是一个错误或信息页面,你能在浏览器中打开客户端请求的 url 吗?

标签: c# asp.net-web-api


【解决方案1】:

如果您想返回文件,请不要从操作中返回 byte[],因为它已编码为 base64。您可以在客户端解码base64 字符串,或者更好地使用File 方法

[HttpGet("{id}")]
public ActionResult Get(Guid id)
{
    var files = Directory.GetFiles(@"Pictures\");
    foreach (var file in files)
    {
        if (file.Contains(id.ToString()))
        {
            return File(System.IO.File.ReadAllBytes(file), "image/jpeg");
        }
    }
    return null;
}

【讨论】:

  • @w0051977 这个答案客户端应该保持不变。试试看
  • 您是说在我的原始帖子中使用客户端代码吗?谢谢。
猜你喜欢
  • 2014-03-02
  • 2017-09-11
  • 2017-01-03
  • 2017-05-22
  • 1970-01-01
  • 1970-01-01
  • 2014-04-04
  • 1970-01-01
相关资源
最近更新 更多