CSS Workaround for BlazorInputFile

Ray HuangOver the past few weeks, I’ve been working on updating an old app (or personal website rather) that I developed by rewriting it in ASP.NET Core Blazor.  I must say, Blazor, has made my life much easier since everything can be written in C#, and I’ve had to use very little Javascript to implement the same features my old site had.  (My old site was very reliant on Javascript and AJAX calls.)  I did run into some issues though and wanted to share this quick tip for those trying to implement an upload feature. 

Instead of reinventing the wheel, I decided to see what solutions were available out there and went with Steven Sanderson’s BlazorInputFile.  I won’t go into details on how to implement it as there are already some great tutorials and videos out there. However, I did run into a weird issue or glitch where the “No file chosen” text in the control would not change despite having selected a file. And I also ran into various quirks where it changed properly and remained that way or would sometimes flash the change and then revert back to the “No file chosen” text.

I spent quite a bit of time trying to find the root cause of the issue but eventually gave up and implemented a workaround since this is probably not the final version of BlazorInputFile.  The workaround is quite simple.  It just uses CSS to hide the text, and then I show the filename by referencing the Name property of the file selected.  The entire code for my Razor component is below: 

page "/" 
@using BlazorInputFile 

<InputFile OnChange="HandleFileSelected" /> 
<br /> 
<br /> 
<strong>File Selected: </strong> 
@if (file != null) 
{ 
    @file.Name 
}

@code { 
    private IFileListEntry file;

    private void HandleFileSelected(IFileListEntry[] files) 
    { 
        file = files.FirstOrDefault();
    }          
}

And the CSS markup which I added to /wwwroot/css/site.css is very short: 

/* Removes "No File Chosen" in File Input Control */
input[type='file'] {
  color:transparent;
}

The final output looks like this after a file is selected. 

Please note the solution I posted is only partial.  You’ll have to add the “plumbing” so to speak by following the tutorial links I gave above. 

I also want to take this opportunity to mention that Everleap is “Blazor” ready since we support ASP.NET Core, and you can enable WebSockets at any time through our Control Panel.  Blazor uses SignalR which is reliant on WebSockets in order to work.

Visit Everleap to learn more about our .NET Core cloud hosting solutions.

Rate this article
   

No responses yet

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.



oui décor