thankyoussd
thankyoussd

Reputation: 2451

Using Azure Function .NET5 and HttpRequestData, how to handle file upload (form data)?

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?

Upvotes: 20

Views: 10290

Answers (1)

Jason Pan
Jason Pan

Reputation: 21918

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;
    }

Upvotes: 20

Related Questions