【问题标题】:Missing data when uploading/downloading image上传/下载图像时缺少数据
【发布时间】:2021-11-05 00:59:14
【问题描述】:

我创建了一个简单的控制器,用于上传和获取(静态)缓存图像。我知道拥有静态字节数组不是最佳做法,但这只是为了测试目的。

它按预期工作,只是当我尝试下载图像时,图像中总是丢失大约 60-80% 的数据。

[Route("image")]
public class CameraController : ControllerBase
{
    private static byte[] latestImageData;

    [HttpPost("upload")]
    public async Task<ActionResult> PostData()
    {
        if(HttpContext.Request.ContentType == "image/jpeg")
        {
            var contentLength = Convert.ToInt32(HttpContext.Request.ContentLength);

            latestImageData = new byte[contentLength];
            await HttpContext.Request.Body.ReadAsync(latestImageData);
        }

        return NoContent();
    }

    [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
    [HttpGet("get")]
    public ActionResult GetImage()
    {
        if (latestImageData != null)
        {

            return File(latestImageData, "image/jpeg");
        }
        else
            return NoContent();
    }
}

这是我尝试下载图像时得到的结果:

有什么想法吗?

【问题讨论】:

  • ReadAsync 将读取 高达 contentLength 字节。它将返回它读取的字节数。 Documented here: "其 Result 属性的值包含读入缓冲区的总字节数。如果当前没有那么多字节,结果值可能小于缓冲区中分配的字节数可用,如果已到达流的末尾,则可以为 0(零)。”
  • @Llama 好的,如何让它们可供阅读?为什么它们不可用?
  • @Felix 您的latestImageData 有问题。通常我通过表单数据上传文件,而不是二进制文件。你可以试试看。
  • 您可以使用 Jon Skeet 在this answer 中的方法作为快速而肮脏的解决方案。或者这个alternative answer。请注意,您可以将 ReadCopyTo 替换为 await ReadAsyncawait CopyToAsync 以利用 async/await 模式。
  • @JasonPan 我正在从另一个应用程序接收数据,所以很遗憾我无法更改。

标签: c# asp.net-core .net-core upload .net-5


【解决方案1】:

this answer 找到我的问题的答案,感谢 cmets 中的Llama

    [HttpPost("upload")]
    public async Task<ActionResult> PostData()
    {
        if(HttpContext.Request.ContentType == "image/jpeg")
        {
            using (var ms = new MemoryStream())
            {
                await HttpContext.Request.Body.CopyToAsync(ms);

                latestImageData = ms.ToArray();
            }
        }

        return NoContent();
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-01
    • 1970-01-01
    • 2018-06-29
    • 2013-02-07
    相关资源
    最近更新 更多