如何从 Azure Functions v2 中的请求正文获取图像数据并转换为流



我需要将发送到 Azure 函数 v2 的图像作为流读取,然后将该流传递给方法以处理图像。

我尝试了几种方法,即。 来自另一个问题或这篇博文,但它们都不起作用 - 每次传递给该方法的 Stream 都有无效数据时。 另外,如果我将请求正文读取为字符串,它会显示一些废话。我认为最合乎逻辑的最终解决方案发布在下面:

public async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)]
HttpRequest req,
ILogger log)
{
Product product;
using (MemoryStream ms = new MemoryStream())
{                
await req.Body.CopyToAsync(ms);
ms.Seek(0, SeekOrigin.Begin);
//Then I need to pass Stream to another method that calls Azure Custom Vision endpoint
product = await _identifyService.IdentifyProduct(ms);
}
}

我还尝试了其他几种方法,即:

MemoryStream ms = new MemoryStream();
await req.Body.CopyToAsync(ms);
byte[] imageBytes = ms.ToArray();
log.LogInformation(imageBytes.Length.ToString());
var memoryStream = new MemoryStream(imageBytes);
memoryStream.Seek(0, SeekOrigin.Begin);
// Then pass memoryStream to the method.

或阅读要求。正文为字符串与流阅读器。这些方法都没有奏效。

使用 ajax 完成的来自 React 应用程序的请求看起来或多或少是这样的(缩短它以更具可读性):


file: File = .... //File from form
const reader = new FileReader();
reader.readAsBinaryString(file);
var binary = reader.result;
fetch(`${API_URL}/IdentifyProduct`, {
method: 'post',
body: binary
}).then(function (response) {
return response.json();
})

也许有人有类似的问题并有解决方案,因为我没有任何其他想法如何让它工作。

1. 如果您的图像数据在表单中,您可以使用以下内容:

MemoryStream ms = new MemoryStream();
req.Form.Files[0].CopyTo(ms);
ms.Position = 0;

这将获得您的 post 请求中的第一张图像。

2. 如果您的图像数据被放入二进制请求中,

只需使用req.Body就可以了。req.Body是流。

最终我想出了一个解决方案。我以错误的方式发送请求。事实证明,文件可以在没有任何准备的情况下以正文形式发送。所以现在JS看起来像这样:

file: File = .... //File from form
fetch(`${API_URL}/IdentifyProduct`, {
method: 'post',
body: file
}).then(function (response) {
return response.json();
})

然后在 C# 的 Azure 函数中读取它:

public async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)]
HttpRequest req,
ILogger log)
{
Product product = await _identifyService.IdentifyProduct(req.Body);
}

最新更新