简体   繁体   English

如何从 Azure Function App 中的请求正文中检索字节数据

[英]How to retrieve bytes data from request body in Azure Function App

In Python, I converted an image into bytes.在 Python 中,我将图像转换为字节。 Then, I pass the bytes to an Azure HTTP Trigger function app endpoint URL (Azure Portal) like this, just like usual when calling Azure cognitive services.然后,我像这样将字节传递给 Azure HTTP 触发器函数应用端点 URL(Azure 门户),就像调用 Azure 认知服务时一样。

image_path = r"C:\Users\User\Desktop\bicycle.jpg"
image_data = open(image_path, "rb").read()
print(len(image_data)) # print length to compare later
url = "https://xxxx.azurewebsites.net/api/HTTPTrigger1........."
headers    = {'Content-Type': 'application/octet-stream'}
response = requests.post(url, headers=headers,
                             data=image_data)

However, I have no idea on how to retrieve the bytes data in the function app on Azure Portal.但是,我不知道如何在 Azure 门户上的函数应用中检索字节数据。 I tried the following (C#) but it did not work.我尝试了以下(C#),但没有奏效。 It seems like ReadToEndAsync() is not meant to read bytes data from request body? ReadToEndAsync()似乎不是从请求正文中读取字节数据? Or is it because of HttpRequest ?还是因为HttpRequest

public static async Task<IActionResult> Run(HttpRequest req, ILogger log)
{
    string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
    byte[] imageBytes = Encoding.ASCII.GetBytes(requestBody); 
    log.LogInformation(imageBytes.Length.ToString());
    // the length logged is totally not the same with len(image_data) in Python

    //ignore the following lines (not related)
    return name != null
    ? (ActionResult)new OkObjectResult("OK")
    : new BadRequestObjectResult("Please pass a name on the query string or in the request body");
}

Any idea about this?对此有什么想法吗? I do know a workaround using base64 string but I'm just really curious about how Azure cognitive services do it!我知道使用 base64 字符串的解决方法,但我真的很好奇 Azure 认知服务是如何做到的!

Thanks in advance.提前致谢。

Do not use ReadToEndAsync() , instead, use MemoryStream() .不要使用ReadToEndAsync() ,而是使用MemoryStream() ReadToEndAsync() is used to read string buffer which can mess up the incoming bytes data. ReadToEndAsync()用于读取字符串缓冲区,这可能会弄乱传入的字节数据。 Use CopyToAsync() and then convert the memory stream into bytes array to preserve the incoming bytes data.使用CopyToAsync()然后将内存流转换为字节数组以保留传入的字节数据。

public static async Task<HttpResponseMessage> Run(HttpRequest req, ILogger log)
{
    //string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
    MemoryStream ms = new MemoryStream(); 
    await req.Body.CopyToAsync(ms);
    byte[] imageBytes = ms.ToArray();
    log.LogInformation(imageBytes.Length.ToString());


    // ignore below (not related)
    string finalString = "Upload succeeded";
    Returner returnerObj = new Returner();
    returnerObj.returnString = finalString;
    var jsonToReturn = JsonConvert.SerializeObject(returnerObj);

    return new HttpResponseMessage(HttpStatusCode.OK) {
        Content = new StringContent(jsonToReturn, Encoding.UTF8, "application/json")
    };
}

public class Returner
{
    public string returnString { get; set; }
}

Reference/Inspired by: https://weblog.west-wind.com/posts/2017/sep/14/accepting-raw-request-body-content-in-aspnet-core-api-controllers参考/灵感来源: https : //weblog.west-wind.com/posts/2017/sep/14/accepting-raw-request-body-content-in-aspnet-core-api-controllers

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用带有请求正文数据的 POST 方法使用 Azure 函数调用外部 api - How to call external api with Azure function with POST method with request body data 如何在Azure Functions v2中从请求主体获取图像数据并将其转换为Stream - How to get image data from request body in Azure Functions v2 and convert to Stream EventHub Azure Function 触发正确,但 EventData.Body 为 0 字节 - EventHub Azure Function triggers correctly but EventData.Body is 0 bytes POST上的azure函数请求正文为null - azure function request body is null on POST 如何从Azure移动服务request.respond(statusCode,body)获取正文内容 - How can you get the body content from a azure mobile services request.respond(statusCode, body) 通过托管标识从 c# Azure 函数检索配置值的 Azure 应用程序配置不起作用 - Azure App Configuration to retrieve configuration values from c# Azure function via Managed Identity is not working Azure 函数 Http 触发器验证正文数据 - Azure Function Http Trigger validating body data 如何检索Oracle过程或函数的主体 - How to retrieve the body of an Oracle procedure or function 如何在日期和时间之间从azure表存储中检索数据 - How to retrieve data from azure table storage between date and time 如何使用Core(SQL)API从Azure Cosmos Db检索数据 - How to retrieve data from Azure Cosmos Db with Core(SQL) API
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM