Search code examples
azure-functionsswagger-uiopenapi

Azure Functions OpenApi extensions File Upload POST request


Is there a way of decorating a function so that the generated swagger UI will allow the user to select a file for upload

I have a new function app with the code necessary to upload a file and store that file away, but I can't figure out how to get the OpenAPI extensions to correctly document that API in the generated swagger UI.

Thanks.


Solution

  • Here is one of the workarounds that you can try

    For instance I have considered file my response to be an image/png and here is my function OpenAPI Function

        
            [FunctionName(nameof(SampleFunction.Run))]
            [OpenApiOperation(operationId: "run", tags: new[] { "multipartformdata" }, Summary = "Transfer image through multipart/formdata", Description = "This transfers an image through multipart/formdata.", Visibility = OpenApiVisibilityType.Advanced)]
            [OpenApiSecurity("function_key", SecuritySchemeType.ApiKey, Name = "code", In = OpenApiSecurityLocationType.Query)]
            [OpenApiRequestBody(contentType: "multipart/form-data", bodyType: typeof(MultiPartFormDataModel), Required = true, Description = "Image data")]
            [OpenApiResponseWithBody(statusCode: HttpStatusCode.OK, contentType: "image/png", bodyType: typeof(byte[]), Summary = "Image data", Description = "This returns the image", Deprecated = false)]
            public static async Task<IActionResult> Run(
                [HttpTrigger(AuthorizationLevel.Function, "POST", Route = "form/multipart")] HttpRequest req,
                ILogger log)
            {
                var files = req.Form.Files;
                var file = files[0];
    
                var content = default(byte[]);
                using (var ms = new MemoryStream())
                {
                    await file.CopyToAsync(ms).ConfigureAwait(false);
                    content = ms.ToArray();
                }
    
                var result = new FileContentResult(content, "image/png");
    
                return result;
            }
    

    Its Model

    public class MultiPartFormDataModel
        {
            public byte[] FileUpload { get; set; }
        }
    

    Here is the output for Image file :

    enter image description here

    Here is the output for Text file :

    enter image description here

    REFERENCES: Azure Functions Binary Data Transfer via Swagger UI