Recent

6/recent/ticker-posts

Header Ads Widget

File Upload in Blazor

This article shows you upload an image using blazored inputfile

here is 2 project

1. Dot net core Api

2. Blazor App


1. Don net core project is used to store and process the file

to create API that received image

     Open visual studio and create a project by selecting dot net core rest API 

    right-click on Controller and add controller give name FilesController.cs





the FilesController.cs contain following code


using System;

using System.Collections.Generic;

using System.IO;

using System.Linq;

using System.Threading.Tasks;

using Microsoft.AspNetCore.Hosting;

using Microsoft.AspNetCore.Http;

using Microsoft.AspNetCore.Mvc;


namespace apiforfile.Controllers

{

    [Route("api/[controller]")]

    [ApiController]

    public class FilesController : ControllerBase

    {

        IWebHostEnvironment _env;


        public FilesController(IWebHostEnvironment _env)

        {

            this._env = _env;

        }

        [HttpPost("File")]

        public async Task<ActionResult> processfile(IFormFile file)

        {

            var webPath = _env.ContentRootPath;

            var path = Path.Combine(webPath, "Files");

            if (!Directory.Exists(path))

            {

                Directory.CreateDirectory(path);

            }

            var fileName = file.FileName;

            using (var fs = new FileStream(Path.Combine(path, fileName), FileMode.Create, FileAccess.Write))

            {

                file.CopyToAsync(fs).GetAwaiter().GetResult();

            }

            return Ok(new {data=fileName});

        }

    }

}



that's it for API controller


2. For blazored app

Create server side blazored project (you can also create web assmbly)

now add following Nuget packages 

BlazorinputFile

Newtonsoft.json


Now add these link in _Host.cshtml

   <link href="_content/Blazored.Modal/Blazored-modal.css" rel="stylesheet" />

    <script src="_content/Blazored.Modal/Blazored.modal.js"></script>

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



_Host.cshtml




@page "/"

@namespace uploadfile.Pages

@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

@{

    Layout = null;

}


<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="utf-8" />

    <meta name="viewport" content="width=device-width, initial-scale=1.0" />

    <title>uploadfile</title>

    <base href="~/" />

    <link rel="stylesheet" href="css/bootstrap/bootstrap.min.css" />

    <link href="css/site.css" rel="stylesheet" />

    <link href="_content/Blazored.Modal/Blazored-modal.css" rel="stylesheet" />

</head>

<body>

    <app>

        <component type="typeof(App)" render-mode="ServerPrerendered" />

    </app>


    <div id="blazor-error-ui">

        <environment include="Staging,Production">

            An error has occurred. This application may no longer respond until reloaded.

        </environment>

        <environment include="Development">

            An unhandled exception has occurred. See browser dev tools for details.

        </environment>

        <a href="" class="reload">Reload</a>

        <a class="dismiss">🗙</a>

    </div>


    <script src="_framework/blazor.server.js"></script>

    <script src="_content/Blazored.Modal/Blazored.modal.js"></script>

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


</body>

</html>

Create Services By adding class

IFileUpload

and implement this by creating SentFiletoServer

SentFiletoServer

project structure look like this 

image



IFileUpload.cs

using System;

using System.Collections.Generic;

using System.IO;

using System.Linq;

using System.Threading.Tasks;


namespace uploadfile.Services

{

    interface IFileUpload

    {

        public Task<string> UploadFile(MemoryStream ms, string filename);

    }

}


SentFiletoServer.cs


using System;

using System.Collections.Generic;

using System.IO;

using System.Linq;

using System.Net.Http;

using System.Threading.Tasks;

using Newtonsoft.Json;


namespace uploadfile.Services

{

    public class SentFiletoServer : IFileUpload

    {

        private HttpClient client;

        public SentFiletoServer(HttpClient client)

        {

            this.client = client;

        }

        public async Task<string> UploadFile(MemoryStream ms, string filename)

        {

           

            using (var content = new MultipartFormDataContent())

            {

                content.Add(new ByteArrayContent(ms.GetBuffer()), "\"file\"", filename);

                var response = await client.PostAsync("api/Files/File",content);

                if (response.StatusCode == System.Net.HttpStatusCode.OK)

                {

                    return "Upload Success";

                }

                else

                {

                    return "Upload Failed";

                }

            }

        } 

    }

}

Add dependency Injection in Startup.cs




Startup.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Net.Http;

using System.Threading.Tasks;

using Microsoft.AspNetCore.Builder;

using Microsoft.AspNetCore.Components;

using Microsoft.AspNetCore.Hosting;

using Microsoft.AspNetCore.HttpsPolicy;

using Microsoft.Extensions.Configuration;

using Microsoft.Extensions.DependencyInjection;

using Microsoft.Extensions.Hosting;

using uploadfile.Data;

using uploadfile.Services;


namespace uploadfile

{

    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.AddScoped<HttpClient>(s=>

            {

                return new HttpClient { BaseAddress = new Uri("https://localhost:44305/") };

            });

            services.AddRazorPages();

            services.AddServerSideBlazor();

            services.AddSingleton<WeatherForecastService>();

            services.AddScoped<IFileUpload, SentFiletoServer>();

        }


        // 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");

            });

        }

    }

}


Now implement all these in index.razor

@page "/"
@using System.IO
@using BlazorInputFile 
@inject uploadfile.Services.IFileUpload f
<h1>Hello, world!</h1>

Welcome to your new app.

<SurveyPrompt Title="How is Blazor working for you?" />

<InputFile OnChange="HandleFileSelected"></InputFile>
<button @onclick="@(async () => await UploadFIle())" >Upload file</button>
@responseMsg
@code
{
    string responseMsg { get; set; } = "";
    IFileListEntry[] ff;
    MemoryStream filestream = null;
    string filename { get; set; } = "";
    public async Task UploadFIle()
    {
        var data = await f.UploadFile(filestream, filename);
        responseMsg = data;
    }

    async Task HandleFileSelected(IFileListEntry[] files)
    {
        if (files.Count() > 0)
        {
            ff = files;
            filestream = new MemoryStream();
            await ff.FirstOrDefault().Data.CopyToAsync(filestream);
            filename = ff.FirstOrDefault().Name;
        }
    }

}

For video please visit Blazor file upload

Post a Comment

1 Comments

  1. Start by creating a new Blazor component or using an existing one where you want to implement the file upload functionality. Fun Game Ideas In the component's markup, add an input element with the type set to file.

    ReplyDelete

thank you for your comment