1

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(); } } } } 
3
  • In this Microsoft article Blazor file uploads 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. Commented Apr 26, 2022 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 Commented Apr 28, 2022 at 16:33
  • Agree. You might find this .NET bug report 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. Commented Apr 28, 2022 at 22:53

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.