Search code examples
c#blazorblazor-server-sidemudblazor

How get full path file selected with MudFileUpload


In a Page.razor, I have this code:

<MudFileUpload T="IBrowserFile" Accept=".csv" OnFilesChanged="OnFilesChanged" FilesChanged="UploadFiles">
    <ButtonTemplate>
        <MudIconButton HtmlTag="label"
               Icon="@Icons.Material.Filled.AttachFile"
               for="@context">
        </MudIconButton>
    </ButtonTemplate>
</MudFileUpload>

In a Page.razor.cs, I have this code:

private void UploadFiles(IBrowserFile file)
{
    Console.WriteLine(file.Name);
}

public void OnFilesChanged(InputFileChangeEventArgs e)
{
    Console.WriteLine(e.File);
}

I need the full path, because I have to read it (it's a .CSV) to display the content in <input type="text" />. When I select the file, I don't see the full path in IBrowserFile neither in InputFileChangeEventArgs.


Solution

  • You can't read the full path on the user's machine with javascript or blazor for security reasons. Instead of trying to access the file path directly, you can read the file's content on the client-side using JavaScript, and then pass that content to your server-side code.

    If you want to display content inside the <input type="text" /> then you can try to do it this way:

    1. Modify your Page.razor file
    <MudFileUpload T="IBrowserFile" Accept=".csv" OnFilesChanged="OnFilesChanged" FilesChanged="UploadFiles">
        <ButtonTemplate>
            <MudIconButton HtmlTag="label" Icon="@Icons.Material.Filled.AttachFile" for="@context"></MudIconButton>
        </ButtonTemplate>
    </MudFileUpload>
    
    <input type="text" @bind="@csvContent" />
    
    1. Modify your Page.razor.cs code to handle the file upload and read its content:
    private string csvContent;
    
    private async Task UploadFiles(IBrowserFile file)
    {
        using (var reader = new StreamReader(file.OpenReadStream()))
        {
            csvContent = await reader.ReadToEndAsync();
        }
    }
    
    private void OnFilesChanged(InputFileChangeEventArgs e)
    {
        var file = e.File;
        UploadFiles(file); // You can call the asynchronous method here
    }
    

    By following this approach, you can read the CSV file's content and display it in the text input without relying on the file's full path.