简体   繁体   中英

How to receive multipart form data in Azure Function?

This answer explains how one can send multipart form data via HTTP POST in C#:

https://stackoverflow.com/a/19664927/10779

Code quoted from answer:

private async Task<System.IO.Stream> Upload(string actionUrl, string paramString, Stream paramFileStream, byte [] paramFileBytes)
{
    HttpContent stringContent = new StringContent(paramString);
    HttpContent fileStreamContent = new StreamContent(paramFileStream);
    HttpContent bytesContent = new ByteArrayContent(paramFileBytes);
    using (var client = new HttpClient())
    using (var formData = new MultipartFormDataContent())
    {
        formData.Add(stringContent, "param1", "param1");
        formData.Add(fileStreamContent, "file1", "file1");
        formData.Add(bytesContent, "file2", "file2");
        var response = await client.PostAsync(actionUrl, formData);
        if (!response.IsSuccessStatusCode)
        {
            return null;
        }
        return await response.Content.ReadAsStreamAsync();
    }
}

How would you properly receive such a POST request in an Azure function?

It seems the HttpRequest Form property ( req.Form["file1"] ) always gives you a string instead of access to a stream. How do you correctly get the original byte[] data for the "file1" or "file2" key?

The default template creates an Azure function with a HttpRequest parameter. Turns out you can change this to a HttpRequestMessage parameter and then use req.Content.ReadAsMultipartAsync() to read individual multiform parts.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM