Sonam Mohite
Sonam Mohite

Reputation: 903

How to remove uploaded file in Blazor

I am looking to add a remove button to clear selected file.

Can't see any event for removing file

<InputFile OnChange="@OnInputFileChange">

enter image description here

Upvotes: 0

Views: 2409

Answers (1)

Ibrahim Timimi
Ibrahim Timimi

Reputation: 3700

To clear the selected file, you can introduce a key attribute to the InputFile component. By changing this key value, Blazor will re-render the InputFile as a new component thus clearing the selected file.

@page "/"

<form @onsubmit="OnSubmit">
    <InputFile @key=@(inputFileId) OnChange="OnInputFileChange"/>
    <br /><br />
    <button type="button" class="btn btn-secondary" @onclick="ResetInputFile">Reset</button>
    <button type="submit" class="btn btn-primary">Upload Selected File</button>
</form>

@code
{
    private Guid inputFileId = Guid.NewGuid();
    IBrowserFile selectedFile;

    private void ResetInputFile() 
    {
        // Change id so that blazor re-renders InputFile as new component
        inputFileId = Guid.NewGuid();
    }

    private void OnInputFileChange(InputFileChangeEventArgs e)
    {
        selectedFile = e.GetMultipleFiles()[0];
        // Do stuff
        //this.StateHasChanged();
    }

    private async void OnSubmit()
    {
        if (selectedFile != null)
        {
            // Do stuff
        }
        this.StateHasChanged();
    }
}

Output: Reset InputFile - Blazor

Upvotes: 5

Related Questions