MudBlazor

Community Support

Discord

GitHub Discussions

Tools and resources

TryMudBlazor

Templates

Sponsor

Open Collective


Switch to Blazor wasm
Toggle light/dark theme
GitHub repository
Toggle right-to-left/left-to-right

Community Support

Discord

GitHub Discussions

Tools and resources

TryMudBlazor

Templates

Sponsor

Open Collective

File Upload

Example on how to compose a file upload button.

To create a file upload button, we must use two elements: a label and an input.


When we set the for attribute to the same value as the id of the input, we enable the input to be triggered by clicking on the label. So the trick is to style the label to look like a button and hide the input.


So, the styling part is solved. But to handle the files in Blazor without using JavaScript, we need an InputFile component.


If you are working with .Net Core 3.1 or earlier, you should install the nuget package InputFile , created by Steve Sanderson and reference it in your _host.cshtml or index.html (Server Side Blazor or Client Side Blazor).


See more info on how to install it.


After uploading the files, you will receive an IFileListEntry[] and then you will have to manage the upload or make the appropriate validations.



If your project is .Net 5.0, InputFile is a native component and you don't need to install it. See more info here

Use any type of MudButton

Use a MudButton, a MudIconButton or a MudFab with the HtmlTag property set to "label" in combination with a hidden InputFile. That way, the MudButton will render a label element.

0 Files:
Show code example
Edit on TryMudBlazor
Copy Code
View the source on GitHub
<InputFile id="fileInput" OnChange="UploadFiles" hidden multiple />

<MudButton HtmlTag="label"
           Variant="Variant.Filled"
           Color="Color.Primary"
           StartIcon="@Icons.Filled.CloudUpload"
           for="fileInput">
    Upload Files
</MudButton>

<MudFab HtmlTag="label"
        Color="Color.Secondary"
        Icon="@Icons.Filled.Image"
        Label="Load picture"
        for="fileInput" />

<MudFab HtmlTag="label"
        Color="Color.Success"
        Icon="@Icons.Filled.AttachFile"
        for="fileInput" />

<MudIconButton HtmlTag="label"
               Color="Color.Info"
               Icon="@Icons.Filled.PhotoCamera"
               for="fileInput">
</MudIconButton>

@if (files != null)
{
    <MudText Typo="@Typo.h6">@files.Count() File@(files.Count() == 1 ? "" : "s"):</MudText>
    <MudList>
    @foreach (var file in files)
    {
     <MudListItem Icon="@Icons.Filled.AttachFile" @key="@file">
         @file.Name <code>@file.Size bytes</code>
     </MudListItem>
    }
    </MudList>
}
@code
{
    IList<IBrowserFile> files = new List<IBrowserFile>();
    private void UploadFiles(InputFileChangeEventArgs e)
    {
        foreach (var file in e.GetMultipleFiles())
        {
            files.Add(file);
        }
        //TODO upload the files to the server
    }
}

Use a standard label

Use an html label styled to your liking in combination with a hidden InputFile.

Show code example
Edit on TryMudBlazor
Copy Code
View the source on GitHub
<label  style="
        box-shadow: 0 2px 7px #4caf50;
        display: inline-flex;
        width: 150px;
        justify-content: space-around;
        border-radius: 2em;
        color: white;
        border:2px solid;
        cursor: pointer;
        align-items: center;
        padding:16px;
        background-color: #4caf50;"         
       for="fileInput2">
    Upload <MudIcon Icon="@Icons.Filled.CloudUpload"/>
</label>

<InputFile id="fileInput2" OnChange="UploadFiles" hidden multiple />

@if (files != null)
{
    <MudList>
        @foreach (var file in files)
        {
            <MudListItem Icon="@Icons.Filled.AttachFile">
                @file.Name <code>@file.Size bytes</code>
            </MudListItem>
        }
    </MudList>
}
@code
{
    IList<IBrowserFile> files = new List<IBrowserFile>();
    private void UploadFiles(InputFileChangeEventArgs e)
    {
        foreach (var file in e.GetMultipleFiles())
        {
            files.Add(file);
        }
        //TODO upload the files to the server
    }
}

Validation

Use the accept attribute to limit the type of files you want.

Show code example
Edit on TryMudBlazor
Copy Code
View the source on GitHub
@inject ISnackbar Snackbar
<InputFile id="fileInput112" OnChange="UploadFiles" hidden multiple accept=".jpg, .jpeg, .png" />

<MudButton HtmlTag="label"
           Variant="Variant.Filled"
           Color="Color.Primary"
           StartIcon="@Icons.Filled.CloudUpload"
           for="fileInput112">
    Upload your images
</MudButton>
@code
{
    private void UploadFiles(InputFileChangeEventArgs e)
    {
        var entries = e.GetMultipleFiles();
        //Do your validations here
        Snackbar.Configuration.PositionClass = Defaults.Classes.Position.TopCenter;
        Snackbar.Add($"Files with {entries.FirstOrDefault().Size} bytes size are not allowed", Severity.Error);
        Snackbar.Add($"Files starting with letter {entries.FirstOrDefault().Name.Substring(0, 1)} are not recommended", Severity.Warning);
        Snackbar.Add($"This file has the extension {entries.FirstOrDefault().Name.Split(".").Last()}", Severity.Info);

        //TODO upload the files to the server
    }
}

Drag and Drop Example

Using the example below, you can compose a drag-and-drop uploader.

Drag and drop files here or click

Show code example
Edit on TryMudBlazor
Copy Code
View the source on GitHub
@inject ISnackbar Snackbar
<style>
    .drag-drop-zone {
        display: flex;align-items: center;justify-content: center;transition: all .4s;min-height: 400px;
    }
    .drag-drop-input {
        position: absolute;width: 100%;height: 90%;opacity: 0;cursor:pointer;
        z-index:2;
    }
    .drag-enter {
        box-shadow: var(--mud-elevation-10);
    }
    .list{
        padding:2em;min-width:100%;
    }
</style>

<MudPaper @ondragenter="@(()=>_dragEnterStyle="drag-enter")"
          @ondragleave="@(()=>_dragEnterStyle=null)"
          @ondragend="@(()=>_dragEnterStyle=null)"
          Class=@("drag-drop-zone "+ _dragEnterStyle)>

    <InputFile OnChange="OnInputFileChanged" multiple  class="drag-drop-input" />

    @if (fileNames.Count() == 0)
    {
        <MudText Typo="Typo.h3">Drag and drop files here or click</MudText> 
    }else
    {
        <MudList Style="padding:2em;width:100%;" Dense="true" >
            @foreach (var file in fileNames)
            {
                <MudListItem @key="@file" >
                   <MudChip Color="Color.Dark" 
                            Style="width:60px; overflow:hidden;" 
                            Text="@(file.Split(".").Last())" />
                   @file
                </MudListItem>}
        </MudList>
    }
</MudPaper>

<MudGrid Justify="Justify.Center" Spacing="4">
    <MudItem>
        <MudButton OnClick="Upload" Disabled="@(!fileNames.Any())" Color="Color.Primary" Variant="Variant.Filled">Upload</MudButton>
    </MudItem>
    <MudItem>
        <MudButton OnClick="@fileNames.Clear" Disabled="@(!fileNames.Any())" Color="Color.Error" Variant="Variant.Filled">Clear</MudButton>
    </MudItem>
</MudGrid>
@code { 
    string _dragEnterStyle;
    IList<string> fileNames = new List<string>();
    void OnInputFileChanged(InputFileChangeEventArgs e)
    {
        var files = e.GetMultipleFiles();
        fileNames = files.Select(f => f.Name).ToList();
    }
    void Upload()
    {
        //Upload the files here
        Snackbar.Configuration.PositionClass = Defaults.Classes.Position.TopCenter;
        Snackbar.Add("TODO: Upload your files!", Severity.Normal);
    }
}
An error has occurred. This application may no longer respond until reloaded. Reload 🗙