.netazure-functionsblazor-server-sidemultipartform-data

Azure Function Form data file upload is NullStream


I have a setup of Blazor server application as frontend and a Azure function app as backend. The user will be uploading a file to the blazor server which directly forwards the file the azure function API.

My problem is that I am not able to forward the provided stream to the HttpClient, which is calling the Azure function app. On the azure function side I receive as "body" as NullStream which does not have data.

I have the following system architecture. The whole code base is in dotnet 8.

Blazor Server application

The user can upload files to the blazor server application. This is working as expected. The formfiles are correctly taken and the stream can be correctly deserialized.

Blazor UI Component


@inject IApiClient ApiClient;


<div style="width: 100%; display: flex; align-items: center; justify-content: center;">

    <label for="inputFile" class="fileUpload">
        <InputFile id="inputFile" OnChange="@LoadFiles" class="d-none" />
    </label>
</div>



@code {

    private long _maxFileSize = 10 * 1024 * 1024;
    private int _maxAllowedFiles = 1;

    private async Task LoadFiles(InputFileChangeEventArgs e)
    {

        foreach (var file in e.GetMultipleFiles(_maxAllowedFiles))
        {
            try
            {
                var fileStream = file.OpenReadStream(_maxFileSize);
                var fileMetaData = await ApiClient.UploadFileAsync(fileStream, file.ContentType, file.Name);
                // omitted
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }
}

Service function which is calling the API backend I don't want to load the whole stream into memory but rather directly provide it as streamcontent to the multipart formdata.

public async Task<FileMetaDataDto> UploadFileAsync(Stream data, string contentType, string fileName)
{
    var content = new MultipartFormDataContent();
    content.Add(new StreamContent(data), fileName);

        // this would copy the whole stream into memory
    // await content.ReadAsStringAsync();

    var result = await _httpClient.PostAsync("api/v1/files", content);

    var json = await result.Content.ReadAsStringAsync();

    var deserialized = JsonSerializer.Deserialize<FileMetaDataDto>(json, SerializerExtensions.DefaultOptions());

    return deserialized ?? new FileMetaDataDto();
}

Azure function Httptrigger

The upload function is a HttpTrigger. The function itself is isolated model version 4.0. I use as an external dependency the following package:

<PackageReference Include="HttpMultipartParser" Version="5.0.0" />

[Function("UploadFile")]
public async Task<HttpResponseData> Run([HttpTrigger(AuthorizationLevel.Function, "post", Route = "v1/files")] HttpRequestData req)
{
    try
    {
        var body = req.Body;
        var parsedFormBody = MultipartFormDataParser.ParseAsync(req.Body);
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
    }

    return req.CreateResponse(HttpStatusCode.OK);
}

Testing with Postman / Swagger

When using the API directly with postman or Swagger the Azure function API behaves correctly. But I also noticed that both are loading files first into memory and sending the whole data at once. In this case the req.Body is of type MemoryStream.

Loading data in memory in Blazor server

The same works if I upload the whole user provided file firs into memory (e.g. copying to a MemoryStream or calling "await content.ReadAsStringAsync();"

Related questions

Using Azure Function .NET5 and HttpRequestData, how to handle file upload (form data)? My starting point was this question, but it did not solve the problem.

Azure functions - How to read form data Outdated

.net 5 Azure Function multipart file upload issue Uploads the file completely in memory in the frontend.

Next steps

I am uncertain where the error is located

1- Blazor server. Do I use correctly the Httpclient together with Multipart form data? Again I do not want to load the whole stream into memory within the blazor server app.

2- Azure function Is this the correct way to get form data?


Solution

  • I created a Blazor server app as frontend and an Azure function app as backend to upload a file from the Blazor server app to the Function app.

    Code :

    frontend :

    FileUploader.razor :

    @page "/file-uploader"
    @using BlazorApp1.Services
    @inject IApiClient ApiClient
    <div style="width: 100%; display: flex; align-items: center; justify-content: center; flex-direction: column;">
        <label for="inputFile" class="fileUpload">
            <InputFile id="inputFile" OnChange="@OnInputFileChange" />
        </label>
        <button @onclick="UploadFile" disabled="@(!isFileSelected)">Upload</button>
    </div>
    @code {
        private IBrowserFile selectedFile;
        private FileMetaDataDto fileMetaData;
        private bool isFileSelected = false;
        private long _maxFileSize = 10 * 1024 * 1024;
        private int _maxAllowedFiles = 1;
        private void OnInputFileChange(InputFileChangeEventArgs e)
        {
            if (e.FileCount > 0)
            {
                selectedFile = e.GetMultipleFiles(_maxAllowedFiles).FirstOrDefault();
                isFileSelected = selectedFile != null;
            }
        }
        private async Task UploadFile()
        {
            if (selectedFile != null)
            {
                try
                {
                    var fileStream = selectedFile.OpenReadStream(_maxFileSize);
                    fileMetaData = await ApiClient.UploadFileAsync(fileStream, selectedFile.ContentType, selectedFile.Name);
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Error uploading file: {ex.Message}");
                }
            }
        }
    }
    

    ApiClient.cs :

    using System.Text.Json;
    namespace BlazorApp1.Services
    {
        public class ApiClient : IApiClient
        {
            private readonly HttpClient _httpClient;
            public ApiClient(HttpClient httpClient)
            {
                _httpClient = httpClient ?? throw new ArgumentNullException(nameof(httpClient));
            }
            public async Task<FileMetaDataDto> UploadFileAsync(Stream data, string contentType, string fileName)
            {
                var content = new MultipartFormDataContent();
                content.Add(new StreamContent(data), "file", fileName); 
                var result = await _httpClient.PostAsync("api/v1/files", content);
                result.EnsureSuccessStatusCode(); 
                var json = await result.Content.ReadAsStringAsync();
                var deserialized = JsonSerializer.Deserialize<FileMetaDataDto>(json, SerializerExtensions.DefaultOptions());
    
                return deserialized ?? new FileMetaDataDto();
            }
        }
    }
    

    Backend :

    UploadFileFunction.cs :

    using System.Net;
    using System.Text.Json;
    using HttpMultipartParser;
    using Microsoft.Azure.Functions.Worker;
    using Microsoft.Azure.Functions.Worker.Http;
    using Microsoft.Extensions.Logging;
    
    public class UploadFileFunction
    {
        private readonly ILogger<UploadFileFunction> _logger;
        private readonly string _uploadFolderPath;
        public UploadFileFunction(ILogger<UploadFileFunction> logger)
        {
            _logger = logger;
            _uploadFolderPath = Path.Combine(Environment.CurrentDirectory, "UploadedFiles"); 
            if (!Directory.Exists(_uploadFolderPath))
            {
                Directory.CreateDirectory(_uploadFolderPath);
            }
        }
        [Function("UploadFileFunction")] 
        public async Task<HttpResponseData> Run([HttpTrigger(AuthorizationLevel.Function, "post", Route = "v1/files")] HttpRequestData req)
        {
            var response = req.CreateResponse(HttpStatusCode.OK);
            try
            {
                var parsedFormBody = await MultipartFormDataParser.ParseAsync(req.Body);
                var file = parsedFormBody.Files.FirstOrDefault();
                if (file != null)
                {
                    var fileName = file.FileName;
                    var fileStream = file.Data;
                    var filePath = Path.Combine(_uploadFolderPath, fileName);
                    using (var fileStreamDestination = File.Create(filePath))
                    {
                        await fileStream.CopyToAsync(fileStreamDestination);
                    }
                    _logger.LogInformation($"File {fileName} uploaded successfully at {filePath}");
                    var fileMetaData = new FileMetaDataDto
                    {
                        FileName = fileName,
                        FileSize = fileStream.Length
                    };
                    var jsonResponse = JsonSerializer.Serialize(fileMetaData);
                    response.Headers.Add("Content-Type", "application/json");
                    await response.WriteStringAsync(jsonResponse);
                }
                else
                {
                    _logger.LogWarning("No file uploaded.");
                    response.StatusCode = HttpStatusCode.BadRequest;
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error processing file upload");
                response.StatusCode = HttpStatusCode.InternalServerError;
            }
            return response;
        }
    }
    public class FileMetaDataDto
    {
        public string FileName { get; set; }
        public long FileSize { get; set; }
    }
    

    Browser Output :

    I uploaded a file from the Blazor server app to the Function app in the browser as below,

    enter image description here

    enter image description here

    Postman :

    I uploaded a file to the function app from the Postman as below,

    enter image description here

    Function app Output :

    I successfully uploaded the files to the function app from both the Blazor server app UI and Postman.

    enter image description here

    Here are successfully saved files to the Function app directory as below:

    enter image description here