0

I'm trying to post a model with an image file and other data from my PWA to my ASP.NET Core Web Api. I succeed with the Api and Postman, but I can't get it working from the PWA. Furthermore, the model should include an IFormFile but the InputFile control returns an IBrowserFile which I cannot cast.

This is a simplified model:

public class ImageUploadModel
{
    public string Details { get; set; }
    public IFormFile Image { get; set; }
}

This is the simplified Api controller:

[HttpPost]
public async Task<IActionResult> UploadModel([FromForm] ImageUploadModel imageUploadModel)
{
    var details = imageUploadModel.Details;
    var image = imageUploadModel.Image;
} 

and here the index.razor test page on the blazor PWA:

@page "/"

<div>
    <InputFile OnChange="@ChangeHandler" />
</div>
<div>
    <button @onclick="Upload">Upload</button>
</div>

@code {
    public IBrowserFile? image;

    private void ChangeHandler(InputFileChangeEventArgs e)
    {
        image = e.File;
    }
    
    private async Task Upload() {

        var model = new imageUploadModel(){
            Details = "foo",
            Image = image
        }
        
        using (var httpClient = new HttpClient())
            {
                using (var response = await httpClient.PostAsJsonAsync("...api url...", model))
                    {
                        response.EnsureSuccessStatusCode();
                        apiResponse = await response.Content.ReadAsStringAsync();
                    }
            }
    }
}
H H
  • 263,252
  • 30
  • 330
  • 514
Matias Masso
  • 1,670
  • 3
  • 18
  • 28
  • In this Microsoft article [Blazor file uploads](https://learn.microsoft.com/en-us/aspnet/core/blazor/file-uploads?view=aspnetcore-6.0&pivots=webassembly) they stream file content to the server. I've not seen this done with PostAsJsonAsync. Looking at the details of your file upload in the browser dev console might help pinpoint the problem. – Yogi Apr 26 '22 at 23:51
  • Thanks Yogi, all articles talk about uploading iFormFiles with no complementary data or with it but client is not a Blazor PWA. I'm afraid I will have to go for the traditional way to post multipart formdata – Matias Masso Apr 28 '22 at 16:33
  • Agree. You might find this [.NET bug report](https://github.com/dotnet/aspnetcore/issues/39087) interesting as it concerns uploading images with Blazor PWA. If you scroll to the bottom they acknowledge the problem and provide a workaround. Anyway, hopefully it will give you some ideas to try. – Yogi Apr 28 '22 at 22:53

0 Answers0