File Uploads With Blazor

If you are new to Blazor, I recommend please you read Getting Started with Blazor, post first.

Introduction

In this post, we are going to upload a file using Blazor in Visual Studio 2019.

Prerequisites

  • Install the .NET Core 2.1 SDK from here.
  • Install the latest preview of Visual Studio 2017 (15.7) from here or Visual Studio 2019 from here.
  • Install ASP.NET Core Blazor Language Services extension from here.

Create a new project

Open Visual Studio 2019, and select “Create a new project”.

Select “Blazor App”.

Click on the “Next” button and set the proper Name and path for the project.

Click on the “Create” button and select the “Blazor Server App” to create a project.

Once a project is created, Install “BlazorInputFile” NuGet from Tools > Manage NuGet Package for Solution.. or execute below command in Package Manager Console.

Install-Package BlazorInputFile -Version 0.1.0-preview-00002

Create a new Razor Component namely “FileInput.razor” by right click on the Pages folder and copy below code and paste in that file.

@page "/fileInput"
@using FileUploadBlazor.Services
@inject IFileUpload fileUpload
<h3>FileInput</h3>

<InputFile OnChange="HandleFileSelected" />

@if (file != null)
{
    <p>Name: @file.Name</p>
    <p>Size in bytes: @file.Size</p>
    <p>File type: @file.Type</p>
}


@code {
    IFileListEntry file;

    async Task HandleFileSelected(IFileListEntry[] files)
    {
        file = files.FirstOrDefault();
        if (file != null)
        {
            await fileUpload.UploadAsync(file);
        }
    }
}

Add a link to this component in “NavMenu.razor” component.

<li class="nav-item px-3">
           <NavLink class="nav-link" href="fileInput" Match="NavLinkMatch.All">
               <span class="oi oi-home" aria-hidden="true"></span> File Input
           </NavLink>
       </li>

Add Below namespaces inside “_imports.razor” component.

@using BlazorInputFile
@using System.IO

Add script reference inside “_Host.cshtml” file.

<script src="_content/BlazorInputFile/inputfile.js"></script>

Create two new folders namely “Services” and “Upload” in the root folder. In the Services folder, we will write business logic and the Upload folder will use to store uploaded files.

In Services folder, Create a new interface namely “IFileUpload” and copy below code and paste there.

using BlazorInputFile;
using System.Threading.Tasks;

namespace FileUploadBlazor.Services
{
    public interface IFileUpload
    {
        Task UploadAsync(IFileListEntry file);
    }
}

Now create a class in the same folder namely “FileUpload” which extends from the “IFileUpload” interface. Copy below code and paste in that class.

using BlazorInputFile;
using Microsoft.AspNetCore.Hosting;
using System.IO;
using System.Threading.Tasks;

namespace FileUploadBlazor.Services
{
    public class FileUpload : IFileUpload
    {
        private readonly IWebHostEnvironment _environment;
        public FileUpload(IWebHostEnvironment env)
        {
            _environment = env;
        }
        public async Task UploadAsync(IFileListEntry fileEntry)
        {
            var path = Path.Combine(_environment.ContentRootPath, "Upload", fileEntry.Name);
            var ms = new MemoryStream();
            await fileEntry.Data.CopyToAsync(ms);
            using (FileStream file = new FileStream(path, FileMode.Create, FileAccess.Write))
            {
                ms.WriteTo(file);
            }
        }
    }
}

Open Startup.cs class and add the below lines in the “ConfigureServices” method.

services.AddScoped<IFileUpload, FileUpload>();

which needed below namespaces

using FileUploadBlazor.Services;

The full code of Startup.cs class looks like this.

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using FileUploadBlazor.Services;

namespace FileUploadBlazor
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddRazorPages();
            services.AddServerSideBlazor();
            services.AddScoped<IFileUpload, FileUpload>();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapBlazorHub();
                endpoints.MapFallbackToPage("/_Host");
            });
        }
    }
}

And we have done, Now press the “F5” key and upload a file.

Output

If you want to learn CRUD operation in Blazor please visit here. also can read about sorting table from here.

3 Comments

  1. Hairstyles Women

    Hi my loved one! I wish to say that this post is amazing, great written and include approximately all important infos. I would like to peer extra posts like this .

    0
    0
    Reply
  2. Hairstyles

    Hi there! Someone in my Myspace group shared this site with us so I came to give it a look. I’m definitely loving the information. I’m bookmarking and will be tweeting this to my followers! Great blog and fantastic style and design.

    0
    0
    Reply
    1. Thanks for the feedback!

      0
      0
      Reply

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories