15

The older Azure Function gives access to HttpRequest, which allows us to access the uploaded files via req.Form.Files etc.

The isolated .NET5 Azure Function uses HttpRequestData instead, which does not give access to the Form. How do I extract the uploaded files posted to the function?

thankyoussd
  • 1,875
  • 1
  • 18
  • 39
  • There is no built-in support for multipart/form-data. Why? No idea. Seems Azure Functions for .NET5 was maybe a bit premature. You can piece together a solution from this [question and answer](https://stackoverflow.com/questions/66923811/net-5-azure-function-multipart-file-upload-issue). – Andy Jun 03 '21 at 04:23
  • 1
    @Andy Use `HttpMultipartParser.ParseAsync(req.Body)` can get files. – Jason Pan Jun 03 '21 at 06:09
  • 1
    eh -- that's not maintained by Microsoft. That's a 3rd party. I don't know why you'd couple to a 3rd party that will lose interest in such a thing in probably 3 months. My comment still stands: It's not built-in... you have to implement it... *somehow*. – Andy Jun 03 '21 at 13:30

1 Answers1

15

You can add <PackageReference Include="HttpMultipartParser" Version="5.0.0" /> in your .csproj file. And use var parsedFormBody = MultipartFormDataParser.ParseAsync(req.Body);, you will get your files.

In postman.

enter image description here

When debug

enter image description here

Below is my test code.

[Function("test")]
public static HttpResponseData Run1([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post")] HttpRequestData req,
        FunctionContext executionContext
        )
    {
        // get query params
        var testvalue=executionContext.BindingContext.BindingData["testparams"];
        // get form-body        
        var parsedFormBody =  MultipartFormDataParser.ParseAsync(req.Body);
        var file=parsedFormBody.Result.Files[0];

        var response = req.CreateResponse(HttpStatusCode.OK);
        response.Headers.Add("Content-Type", "text/plain; charset=utf-8");

        response.WriteString("Welcome to Azure Functions!");

        return response;
    }
Jason Pan
  • 15,263
  • 1
  • 14
  • 29
  • Wow thank you for saving my full day struggle. Where can I find any related documentation on this? How else a new developer like me is supposed to figure something like this out! – thankyoussd Jun 03 '21 at 06:38
  • 2
    @thankyoussd https://github.com/Azure/azure-functions-dotnet-worker/issues/366 – Jason Pan Jun 03 '21 at 06:51
  • I'm using the same approach but with larger PDF files my function host crashes withouth even calling the trigger. Any ideas? – Rainer Schuster Aug 13 '21 at 13:22
  • 1
    @RainerSchuster I think there is a limit on the file size with functions especially for the Consumption tier. – Andrei Bazanov Jan 26 '22 at 15:10