'Blazor PWA Inputfile and send it to API Server

I am working on a system composed of a Blazor PWA app and an API Server. A user should be able to upload a file (a simple text file) through an InputFile component in the Blazor app and in turn, the Blazor app send it to the Backend Server. I am using the code that follows but it is not working. The post request from LoadFile is sent but on the server side the object is empty:

This is the code in the blazor component:

@inject HttpClient client //client has BaseAddress set to "http://localhost:5050"

<div style="width:800px">
  <EditForm Model="@_data" OnValidSubmit="@Send" class="card card-body bg-light mt-5">
    <DataAnnotationsValidator />
    <ValidationSummary />
    

    <div class="col-md-10">
        <InputFile OnChange="@LoadFile" />
    </div>


    <div class="form-group row">
        <div class="col-md-12 text-right">
            <button type="submit" class="btn btn-success">Send</button>
        </div>
    </div>
  </EditForm>
</div>

@code {
    private async Task LoadFile(InputFileChangeEventArgs file)
    {
        var streamContent = new StreamContent(file.File.OpenReadStream());
        streamContent.Headers.ContentType = new MediaTypeHeaderValue(file.File.ContentType);
        form.Add(content:streamContent, name:"file", fileName:file.File.Name);

        var response = await client.PostAsJsonAsync("postdata", form);
    }

    private void Send()
    {
        //Not implemented yet
    }
}

This is the Server side minimal API receiver:

app.MapPost("/postdata", ([FromForm] IEnumerable<IFormFile> files) =>
{
    if (files.Count() > 0)
    {
        return Results.Ok();
    }
    return Results.BadRequest();
});

Any ideas are welcome...



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source