blazor upload file in csharp

To upload a file in Blazor using C#, we need to create a form and use the httpClient to post the file to the web api endpoint. Here's an example:

  1. In your Blazor component, create a form with an input of type file:
<form>
    <input type="file" @onchange="HandleFileUpload" />
    <button type="submit" @onclick="UploadFile">Upload</button>
</form>
134 chars
5 lines
  1. In your component's code, create a property to hold the uploaded file:
main.cs
private IFormFile file;

private void HandleFileUpload(InputFileChangeEventArgs e)
{
    file = e.File;
}
106 chars
7 lines
  1. Create a method to handle the form submission and send the file to the web api endpoint:
main.cs
private async Task UploadFile()
{
    var formData = new MultipartFormDataContent();
    formData.Add(new StreamContent(file.OpenReadStream()), "file", file.FileName);

    using (var httpClient = new HttpClient())
    {
        var response = await httpClient.PostAsync("api/files", formData);

        if (!response.IsSuccessStatusCode)
        {
            // handle error
        }
    }
}
395 chars
16 lines
  1. In your web api controller, create an endpoint to handle the file upload:
main.cs
[HttpPost]
public async Task<IActionResult> UploadFile(IFormFile file)
{
    // do something with the file

    return Ok();
}
127 chars
8 lines

And that's it! You should now be able to upload files from your Blazor app to your web api.

gistlibby LogSnag