【发布时间】: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。请注意,您可以将
Read和CopyTo替换为await ReadAsync和await CopyToAsync以利用 async/await 模式。 -
@JasonPan 我正在从另一个应用程序接收数据,所以很遗憾我无法更改。
标签: c# asp.net-core .net-core upload .net-5