Sujeet Raman

Sujeet Raman

  • 857
  • 927
  • 352k

How to save an edit form with multiple images in blazor

Jan 6 2023 12:27 PM

Hi i am learning blazor and am stuck in some point.I have an edit form having functionality to add multiple image for a record.How can i merge list of images and other data  as a single paylod. i have rough code with me but dont know how to create a model for these two list.i will have add/remove selected image also in future

onfilechange for multuiple images

private async Task OnFilesChanged(InputFileChangeEventArgs e)
{
    var maxAllowedFiles = 3000;

    var format = "image/png";

    foreach (var imageFile in e.GetMultipleFiles(maxAllowedFiles))
    {
        var resizedImageFile = await imageFile.RequestImageFileAsync(format,
            100, 100);
        var buffer = new byte[resizedImageFile.Size];
        await resizedImageFile.OpenReadStream().ReadAsync(buffer);
        var imageDataUrl =
            $"data:{format};base64,{Convert.ToBase64String(buffer)}";

        Medias.Add(new MediaVariantUI
        {
            Content = buffer,
            ImageDataUrl = imageDataUrl,
            ContentType = imageFile.ContentType,
            Name = imageFile.Name,
            Size = imageFile.Size,
        });
    }
}

 below is edit form using mudblazor

<EditForm Model="@characters" OnValidSubmit="HandleSubmit">
    <MudNumericField Label="Id" @bind-Value="character.id" For="@(() => character.id)"></MudNumericField>
    <MudTextField Label="Name" @bind-Value="character.Name" For="@(() => character.Name)" />
    <MudTextField Label="Bio" @bind-Value="character.Bio" For="@(() => character.Bio)" />
    <MudDatePicker Label="Birth Date" @bind-Date="character.BirthDate" />
    <br />
    <InputFile id="fileInput" OnChange="OnFilesChanged" hidden multiple />
    <MudButton HtmlTag="label"
               Variant="Variant.Filled"
               Color="Color.Success"
               StartIcon="@Icons.Filled.CloudUpload"
               for="fileInput">
        Upload Images
    </MudButton>
    <br />
</EditForm>

how i can get one single paylos in HandleSubmit methode? how can i create a model class for these?


Answers (1)