Blazor File Upload (Updated)

 


With the release of .Net 5.0, a new Blazor file upload component was released.  I wanted to replace my old file upload component that I published way back in Oct of 2019, post with the new 5.0 one.

This post is working with the Blazor Server side, but this will work with Web Assembly except you will need a server API to do the actual file upload.


Changes

I started by updating my Blazor project to /net 5.0.  That part was easy.  My next step was to replace the component.  As it turned out, my old component was named the same as the new one:

        <InputFile OnChange="@HandleSelection" />

For the selection handler, I had to make a couple of changes.  The changes were

1. Switched the agreement from IFileListEntry to InputfileChangeEventArg

2. The collection of files that were selected changed from FileListEntry to IBrowserFile.  Working with IBrowser file object does change the information that we have access to like the ContentType.  

3. Remove the GetFileType method and I can use the actual ContentType of the file. 

4. Replaced the Memory stream reading of the file to use the OpenReadStream method right on the new file object.

OLD:

        var ms = new MemoryStream();

        await file.Data.CopyToAsync(ms);

                 

NEW:

        var ms = new MemoryStream();

        await new StreamContent(file.OpenReadStream()).CopyToAsync(ms);

        var fileContent = new StreamContent(file.OpenReadStream());

         ms.WriteTo(newFile);   

That was all that was needed to support the new file upload component.


There were a couple of other changes to make the application better.  

1. Upload any type of file

2. Saves the file to the server and use that URL to display the image

3. Check for max file size

 

Benefits 

By using the .net file upload component, I was able to remove a lot of code, over 500 lines.  Anytime you can reduce the lines of code, it is a very good thing.  This removes you from having to do any maintenance on all that code as well.


Summary

This update was quick and easy and I highly recommend doing it.  The benefits out way the small of time it took.

Anytime you are allowing your users to upload files to your server you need to make sure you take security into account.  This post, File Upload Security provides some guidelines.


[piggy back from]

[source]

Comments

Popular posts from this blog

Yes, Blazor Server can scale!

Blazor new and improved Search Box

Blazor Wizard Step Component