Blog Single - FlexStart Bootstrap Template

How to Add & Remove images in Preview before uploading to Server in .NET Blazor Application

Blazor has InputFile component to upload files. You can use the component and its OnChange event to get the selected files.The component works well if you just want to upload files to the server. But if you want to add files one by one or try to have a preview feature with an option to add or remove files before uploading, a run time error is thrown.

This is because everytime a user selects a new file, the InputFile component removes the previous files and adds the new ones. I doesn't retain the information from the previously added file.

To resolve this, we need generate a new InputFile component each time a file is added and hide all the previous InputFile components.

For using this InputFile component to also preview and select the images to be uploaded, the file content of each previously added file can be stored in a Dictionary with the same key(a unique Guid can be used as key for each new file/image) as another Dictionary of image DataURL's used to display the images. Deleting the records with the same key in both Dictionaries deletes the image File content as well as the preview image.

If you do not want to use two Dictionaries, you can try using a single Dictionary with the key and a Tuple of File content and image DataURL

The Inputfile component's appearance can be modified by placing it within a Div and manipulating it's css.