Real Time File Upload with SignalR in Asp.Net Core


In this article, I will show you how to implement real-time file upload in asp.net core using SignalR to send upload progress feedback.

The sample upload file is a CSV file and can be downloaded here as part of the source code.

Overview
I will be demonstrating how to upload a file in asp.net core using SignalR to send a real-time upload progress feedback to the client. Upload progress will be displayed by a bootstrap progress bar and a counter to display the number of records uploaded.

At the end of this writeup, you will learn
  • Uploading and processing file in asp.net core (CSV file as a case study)
  • Using SignalR to send real-time feedback to the client
  • Calling SignalR methods from server and client sides.

Prerequisites
  • Visual Studio 2019
  • ASP.Net Core 3.0 or latest

SignalR
SignalR is a Microsoft ASP.NET library that allows server code to send asynchronous notifications to client-side web applications. This allows developers to add real-time web functionality to their applications.
For further reading:
  • Lunch visual studio and click on create a new project.
  • In the create new project dialog, select ASP.NET Core Web Application and click next.
  • In the configure your new project dialog, name the project FileUpload then select create.
  • In the Create new ASP.NET Core web Application dialog, select .NET Core and ASP.NET Core 3.0 or latest. Select Web Application (Model-View-Controller) and click Create.
Modify the project Layout like so:


 <!DOCTYPE html>  
 <html lang="en">  
 <head>  
   <meta charset="utf-8" />  
   <meta name="viewport" content="width=device-width, initial-scale=1.0" />  
   <title>@ViewData["Title"] - File-Upload</title>  
   <link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" />  
   <link rel="stylesheet" href="~/css/site.css" />  
 </head>  
  <body>  
    <header>  
      <nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-light bg-white border-bottom box-shadow mb-3">  
        <div class="container">  
          <a class="navbar-brand" asp-area="" asp-controller="Home" asp-action="Index">File-Upload</a>  
          <button class="navbar-toggler" type="button" data-toggle="collapse" data-target=".navbar-collapse" aria-controls="navbarSupportedContent"  
              aria-expanded="false" aria-label="Toggle navigation">  
            <span class="navbar-toggler-icon"></span>  
          </button>  
        </div>  
      </nav>  
    </header>  
    <div class="container">  
      <main role="main" class="pb-3">  
        @RenderBody()  
      </main>  
    </div>  
    <footer class="border-top footer text-muted">  
      <div class="container">  
        &copy; 2019 - FileUpload - <a asp-area="" asp-controller="Upload" asp-action="Privacy">Privacy</a>  
      </div>  
    </footer>  
    <script src="~/lib/jquery/dist/jquery.min.js"></script>  
    <script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>  
    <script src="~/js/site.js" asp-append-version="true"></script>  
    @RenderSection("Scripts", required: false)  
  </body>  
  </html>  

Add the SignalR client library
ASP.NET Core 3.0 shared framework included the SignalR server library but the JavaScript client library is not automatically included in the project. Hence, LibMan(Library Manager) will be used to get the client library from unpkg.

  • In Solution Explorer, right-click the project, select Add > Client-Side Library.
  • In the Add Client-Side Library dialog, select unpkg as the provider.
  • Type @microsoft/signlr@latest for Library.
  • Select Choose specific files, expand the dist/browser folder, and select signalr.js and signalr.min.js.
  • Set Target Location to wwwroot/js/signalr/, and select Install. 



Create a SignalR Hub
  • Right-click the project, select Add > new folder. Name the folder Hubs.
  • In the Hubs folder, create a BroadCastHub.cs class 
  • Modify the BroadCastHub like so:


 using Microsoft.AspNetCore.SignalR;  
 using System.Threading.Tasks;  
 namespace FileUpload.Hubs  
 {  
   public class BroadCastHub: Hub  
   {  
     public Task Feedback(string message)  
     {  
      return Clients.Caller.SendAsync(&quot;feedBack&quot;, message);  
      }  
    }  
  }  

Configure SignalR
Open and modify the Startup.cs file like so:


 using FileUpload.Hubs;  
 using Microsoft.AspNetCore.Builder;  
 using Microsoft.AspNetCore.Hosting;  
 using Microsoft.Extensions.Configuration;  
 using Microsoft.Extensions.DependencyInjection;  
 using Microsoft.Extensions.Hosting;  
 namespace FileUpload  
 {  
   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.  
      public void ConfigureServices(IServiceCollection services)  
      {  
        services.AddControllersWithViews();  
        services.AddSignalR();  
      }  
      // 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("/Home/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.UseAuthorization();  
        app.UseEndpoints(endpoints =>  
        {  
          endpoints.MapControllerRoute(  
            name: "default",  
            pattern: "{controller=Upload}/{action=Index}/{id?}");  
          endpoints.MapHub<BroadCastHub>("/broadcast");  
        });  
      }  
    }  
  }  

Add File Upload Client Code
  • Right-click the controllers folder and select Add > controller > MVC Controller - Empty, then click Add.
  • Name the controller Upload then click  Add.
  • Right-click the Index action then select Add view.
  • Modify the index view like so:


 @{  
   ViewData["Title"] = "File Upload";  
 }  
 <style>  
   .fileUpload {  
     position: relative;  
     overflow: hidden;  
     margin: 0;  
   }  
    .fileUpload input.upload {  
      position: absolute;  
      top: 0;  
      right: 0;  
      margin: 0;  
      padding: 0;  
      font-size: 20px;  
      cursor: pointer;  
      opacity: 0;  
      filter: alpha(opacity=0);  
    }  
  </style>  
  <div class="row">  
  <div class="col-md-6">  
  <div class="input-group">  
  <input class="form-control" disabled="disabled" id="uploadFile" placeholder="" style="height: 36px;" />  
        <br />  
  <div class="input-group-btn">  
  <div class="fileUpload btn btn-info">  
  ...  
            <input accept=".csv" class="upload" id="fileToUpload" multiple="" name="fileToUpload" onchange="fileToUploadOnchange()" type="file" />  
          </div>  
  </div>  
  </div>  
  </div>  
  <input class="btn btn-info btn-sm" id="btnUpload" type="button" value="Upload" />  
  </div>  
  <div class="text-center">  
  <div class="row">  
  <div class="col-md-12">  
  <table class="table table-bordered table-hover" style="width: 100%;">  
          <thead>  
  <tr>  
              <th>S/N</th>  
              <th>Company</th>  
              <th>Category</th>  
              <th>City</th>  
              <th>Funded Date</th>  
              <th>Currency</th>  
              <th>Amount</th>  
            </tr>  
  </thead>  
          <tbody id="tableBody">  
          </tbody>  
        </table>  
  </div>  
  </div>  
  </div>  
  <div class="modal fade" data-backdrop="static" id="progressModal" role="dialog" tabindex="-1">  
  <div class="modal-dialog modal-lg" style="top: 40vh; width: 50%;">  
  <div class="modal-content">  
  <div class="modal-body">  
  <div class="row">  
  <div class="col-md-10">  
  <div class="progress">  
  <div aria-valuemax="100" aria-valuemin="0" aria-valuenow="0" class="progress-bar progress-bar-striped" id="progress_bar" role="progressbar" style="width: 0%;">  
  </div>  
  </div>  
  </div>  
  <div class="col-md-2">  
  Count: <text id="uploadCount">0</text>  
            </div>  
  </div>  
  </div>  
  </div>  
  <!-- / .modal-content -->  
    </div>  
  <!-- / .modal-dialog -->  
  </div>  
  <!-- / .modal -->  
  </pre>  
  </div>  
  <br />  
  <div>  
  <b>Add SignalR to Client Code</b></div>  
  <div>  
  Modify the script section of the view like so:  
  <br />  
  <div>  
  <br />  
  @section Scripts{  
    <script src="~/js/signalr/dist/browser/signalr.js"></script>  
    <script>  
      var connection = new signalR.HubConnectionBuilder().withUrl("/broadcast").build();  
      connection.on("feedBack", function (model) {  
        $("#progress_bar").css("width", `${model.currentPercent}%`);  
        $("#uploadCount").html(model.uploadCount);  
      });  
      connection.start().then(function ()  
      {  
         console.log("Sinalr Connected");  
       }).catch(function (err) {  
         console.log(err.toString());  
       });  
     </script>  
  }  

The above script added reference to the SignalR js file we added using LibMan. Also, the client SignalR connection is configured and started. An event listener feedBack is added to the connection which listens to the message from the server. Upon message received, the width property of the progress bar and the upload count is updated. The event listener feedBack is the method name passed to the SendAsync in the BroadCastHub.

Add Models
  •  Right-click the models folder, select Add > class. Name the class RecordItem. 
  • Modify the file like so:

 namespace FileUpload.Models  
 {  
   public class RecordItem  
   {  
     public string Company { get; set; }  
     public string Date { get; set; }  
     public string Category { get; set; }  
     public string City { get; set; }  
     public string Currency { get; set; }  
      public decimal Amount { get; set; }  
      public string StrAmount  
      {  
        get  
        {  
          return Amount.ToString("#,##0.00;(#,##0.00)");  
        }  
      }  
    }  
  }  

Also, add FeedbackModel to the models folder and modify like so:


 using System;  
 using System.Collections.Generic;  
 namespace FileUpload.Models  
 {  
   public class FeedbackModel  
   {  
     public int currentCount { get; set; }  
     public string currentPercent { get; set; }  
     public int UploadCount { get; set; }  
    }  
  }  

Add the Upload Functionality to the Controller
Inject the IHubContext like so:

  private readonly IHubContext<BroadCastHub> hubContext;  
     public UploadController(IHubContext<BroadCastHub> _hubContext)  
     {  
       hubContext = _hubContext;  
     }  

Add a private method to handle feedback broadcasting from the controller like so:

 private async void SendFeedBack(int currentCount, int UploadCount)  
    {  
       var totalCount = 4;  
       var feedBackModel = new FeedbackModel()  
       {  
         currentCount = currentCount,  
         currentPercent = (currentCount * 100 / totalCount).ToString(),  
         UploadCount = UploadCount,  
       };  
        await hubContext.Clients.All.SendAsync("feedBack", feedBackModel);  
    }  

Next, add the file upload method like so:

  public async Task<JsonResult> UploadFile()  
     {  
       try  
       {  
         var counter = 0;  
         var currentCount = 0;  
         var data = new List<RecordItem>();  
         var postedFile = Request.Form.Files;  
         await Task.Delay(500);  
          currentCount++;  
          SendFeedBack(currentCount, counter);  
          if (postedFile.Count <= 0 || postedFile == null)  
            return Json(new { error = true, message = "Empty File was uploaded" });  
          if (postedFile[0] == null || postedFile[0].Length <= 0)  
          {  
            return Json(new { error = true, message = "Empty File was uploaded" });  
          }  
          await Task.Delay(500);  
          currentCount++;  
          SendFeedBack(currentCount, counter);  
          var fileInfo = new FileInfo(postedFile[0].FileName);  
          var extention = fileInfo.Extension;  
          if (extention.ToLower() != ".csv")  
          {  
            return Json(new { error = true, message = "invalid file format" });  
          }  
          using (StreamReader sr = new StreamReader(postedFile[0].OpenReadStream()))  
          {  
            await Task.Delay(500);  
            currentCount++;  
            SendFeedBack(currentCount, counter);  
            while (!sr.EndOfStream)  
            {  
              String Info = sr.ReadLine();  
              String[] Records;  
              if (Info.Contains('\"'))  
              {  
                var row = string.Empty;  
                var model = Info.Replace("\"", "#*").Split('#');  
                foreach (var item in model)  
                {  
                  var d = item.Replace("*,", ",");  
                  if (d.Contains("*"))  
                  {  
                    row += d.Replace("*", "").Replace(",", "");  
                  }  
                  else  
                  {  
                    row += d;  
                  }  
                }  
                Records = new String[row.Split(new char[] { ',' }).Length];  
                row.Split(new char[] { ',' }).CopyTo(Records, 0);  
              }  
              else  
              {  
                Records = new String[Info.Split(new char[] { ',' }).Length];  
                Info.Split(new char[] { ',' }).CopyTo(Records, 0);  
              }  
              var strAmount = Records[7].ToString().Trim();  
              decimal output;  
              if (string.IsNullOrEmpty(strAmount) || !decimal.TryParse(strAmount, out output)) continue;  
              var datafile = new RecordItem()  
              {  
                Company = Records[1].ToString().Trim(),  
                Category = Records[3].ToString().Trim(),  
                City = Records[4].ToString().Trim(),  
                Date = Records[6].ToString().Trim(),  
                Currency = Records[8].ToString().Trim(),  
                Amount = decimal.Parse(Records[7].ToString().Trim()),  
              };  
              data.Add(datafile);  
              counter++;  
              SendFeedBack(currentCount, counter);  
            }  
            sr.Close();  
            sr.Dispose();  
            await Task.Delay(500);  
            currentCount++;  
            SendFeedBack(currentCount, counter);  
          }  
          await Task.Delay(500);  
          currentCount++;  
          SendFeedBack(currentCount, counter);  
          return Json(new { error = false, data = data });  
        }  
        catch (Exception ex)  
        {  
          return Json(new  
          {  
            error = true,  
            message = ex.InnerException != null ?  
            ex.InnerException.Message : ex.Message  
          });  
        }  
      }  

Note that the Task.Delay(500) was used, this is because we want to add some delays to the upload in other to see the SignalR feedback in action. Do not use this approach in a real application unless otherwise needed.

Wrap Up Client Upload View
To complete the file upload, add the following to the script section:

  $(document).ready(function () {  
       defaultTableContent();  
     })  
     $("#btnUpload").click(function (e) {  
       e.preventDefault();  
       uploadFile();  
     });  
     function defaultTableContent() {  
       var empltyTableTemplate = $("<tr></tr>");  
        var placeholder = "<td colSpan='7'><p>No Data</p></td>";  
        empltyTableTemplate.html(placeholder);  
        $("#tableBody").html(empltyTableTemplate);  
      }  
      function fileToUploadOnchange() {  
        $this = document.getElementById("fileToUpload");  
        fileSelected($this);  
      }  
      function fileSelected(input) {  
        var file = document.getElementById('fileToUpload').files[0];  
        var ext = input.value.split('.');  
        ext = ext[ext.length - 1].toLowerCase();  
        var arrayExtensions = ['csv'];  
        if (arrayExtensions.lastIndexOf(ext.toLowerCase()) == -1) {  
          alert("You can only upload .CSV File");  
          input.value = '';  
          document.getElementById("uploadFile").value = '';  
          return;  
        }  
        document.getElementById("uploadFile").value = file.name;  
        if (file) {  
          var fileSize = 0;  
          if (file.size > 1024 * 1024)  
            fileSize = (Math.round(file.size * 100 / (1024 * 1024)) / 100).toString() + 'MB';  
          else  
            fileSize = (Math.round(file.size * 100 / 1024) / 100).toString() + 'KB';  
        }  
      }  
      function uploadFile() {  
        var file = document.getElementById('fileToUpload').files[0];  
        if (file) {  
          $("#progressModal").modal("show");  
          var url = '@Url.Action("UploadFile", "Upload")';  
          var fd = new FormData();  
          fd.append("fileToUpload", file);  
          var xhr = new XMLHttpRequest();  
          xhr.addEventListener("load", uploadComplete, false);  
          xhr.addEventListener("error", uploadFailed, false);  
          xhr.addEventListener("abort", uploadCanceled, false);  
          xhr.open("POST", url);  
          xhr.send(fd);  
        } else {  
          alert("You are can not upload an empty file");  
        }  
      }  
      function uploadComplete(evt) {  
        var response = JSON.parse(evt.target.response);  
         $("#progressModal").modal("hide");  
         ResetUploadModal();  
        if (response.error) {  
          alert(response.message);  
          return;  
        }  
        populateTableData(response.data);  
      }  
      function populateTableData(data) {  
        if (data.length <= 0) return;  
          $("#tableBody").html('');  
        $.each(data, function (i, val) {  
          let tableRow = $("<tr></tr>");  
          let tablecells = `<td>${i + 1}</td>` +  
            `<td>${val.company}</td>` +  
            `<td>${val.category}</td>` +  
            `<td>${val.city}</td>` +  
            `<td>${val.date}</td>` +  
            `<td>${val.currency}</td>` +  
            `<td>${val.strAmount}</td>`;  
          tableRow.html(tablecells);  
          $("#tableBody").append(tableRow[0]);  
        });  
      }  
      function uploadFailed(evt) {  
        $("#progressModal").modal("hide");  
        ResetUploadModal();  
        alert("There was an error attempting to upload the file");  
      }  
      function uploadCanceled(evt) {  
        $("#progressModal").modal("hide");  
        ResetUploadModal();  
        alert("The upload has been canceled by the user or the browser dropped the connection")  
      }  
      function ResetUploadModal() {  
        document.getElementById("uploadFile").value = '';  
        document.getElementById("fileToUpload").value = null;  
        $("#progressContainer").hide();  
        $("#progress_bar").css("width", "-1%");  
      }  

The Complete view should look like so:

    @{  
      ViewData["Title"] = "File Upload";  
    }  
    <style>  
      .fileUpload {  
        position: relative;  
        overflow: hidden;  
        margin: 0;  
      }  
       .fileUpload input.upload {  
         position: absolute;  
         top: 0;  
         right: 0;  
         margin: 0;  
         padding: 0;  
         font-size: 20px;  
         cursor: pointer;  
         opacity: 0;  
         filter: alpha(opacity=0);  
       }  
     </style>  
     <div class="row">  
       <div class="col-md-6">  
         <div class="input-group">  
           <input id="uploadFile" placeholder="" disabled="disabled" class="form-control" style="height:36px" />  
           <div class="input-group-btn">  
             <div class="fileUpload btn btn-info">  
               <span>...</span>  
               <input type="file" name="fileToUpload" id="fileToUpload" class="upload" onchange="fileToUploadOnchange()" multiple accept=".csv" />  
             </div>  
           </div>  
         </div>  
       </div>  
       <input type="button" class="btn btn-info btn-sm" value="Upload" id="btnUpload" />  
     </div>  
     <p></p>  
     <div class="text-center">  
       <div class="row">  
         <div class="col-md-12">  
           <table class="table table-bordered table-hover" style="width:100%">  
             <thead>  
               <tr>  
                 <th>S/N</th>  
                 <th>Company</th>  
                 <th>Category</th>  
                 <th>City</th>  
                 <th>Funded Date</th>  
                 <th>Currency</th>  
                 <th>Amount</th>  
               </tr>  
             </thead>  
             <tbody id="tableBody">  
             </tbody>  
           </table>  
         </div>  
       </div>  
     </div>  
     <div id="progressModal" class="modal fade modal-center-c" tabindex="-1" role="dialog" data-backdrop="static">  
       <div class="modal-dialog modal-lg" style="width: 50% !important;  top: 40vh;">  
         <div class="modal-content">  
           <div class="modal-body">  
             <div class="row">  
               <div class="col-md-10">  
                 <div class="progress">  
                   <div class="progress-bar progress-bar-striped" role="progressbar" id="progress_bar" style="width: 0%" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100"></div>  
                 </div>  
               </div>  
               <div class="col-md-2">  
                  <span>Count: <text id="uploadCount">0</text></span>  
               </div>  
             </div>  
           </div>  
         </div> <!-- / .modal-content -->  
       </div> <!-- / .modal-dialog -->  
     </div> <!-- / .modal -->  
     @section Scripts{  
       <script src="~/js/signalr/dist/browser/signalr.js"></script>  
       <script>  
         var connection = new signalR.HubConnectionBuilder().withUrl("/broadcast").build();  
         connection.on("feedBack", function (model) {  
           $("#progress_bar").css("width", `${model.currentPercent}%`);  
           $("#uploadCount").html(model.uploadCount);  
         });  
         connection.start().then(function ()  
         {  
           console.log("Sinalr Connected");  
         }).catch(function (err) {  
           console.log(err.toString());  
         });  
         $(document).ready(function () {  
           defaultTableContent();  
         })  
         $("#btnUpload").click(function (e) {  
           e.preventDefault();  
           uploadFile();  
         });  
         function defaultTableContent() {  
           var empltyTableTemplate = $("<tr></tr>");  
           var placeholder = "<td colSpan='7'><p>No Data</p></td>";  
            empltyTableTemplate.html(placeholder);  
            $("#tableBody").html(empltyTableTemplate);  
          }  
          function fileToUploadOnchange() {  
            $this = document.getElementById("fileToUpload");  
            fileSelected($this);  
          }  
          function fileSelected(input) {  
            var file = document.getElementById('fileToUpload').files[0];  
            var ext = input.value.split('.');  
            ext = ext[ext.length - 1].toLowerCase();  
            var arrayExtensions = ['csv'];  
            if (arrayExtensions.lastIndexOf(ext.toLowerCase()) == -1) {  
              alert("You can only upload .CSV File");  
              input.value = '';  
              document.getElementById("uploadFile").value = '';  
              return;  
            }  
            document.getElementById("uploadFile").value = file.name;  
            if (file) {  
              var fileSize = 0;  
              if (file.size > 1024 * 1024)  
                fileSize = (Math.round(file.size * 100 / (1024 * 1024)) / 100).toString() + 'MB';  
              else  
                fileSize = (Math.round(file.size * 100 / 1024) / 100).toString() + 'KB';  
            }  
          }  
          function uploadFile() {  
            var file = document.getElementById('fileToUpload').files[0];  
            if (file) {  
              $("#progressModal").modal("show");  
              var url = '@Url.Action("UploadFile", "Upload")';  
              var fd = new FormData();  
              fd.append("fileToUpload", file);  
              var xhr = new XMLHttpRequest();  
              xhr.addEventListener("load", uploadComplete, false);  
              xhr.addEventListener("error", uploadFailed, false);  
              xhr.addEventListener("abort", uploadCanceled, false);  
              xhr.open("POST", url);  
              xhr.send(fd);  
            } else {  
              alert("You are can not upload an empty file");  
            }  
          }  
          function uploadComplete(evt) {  
            var response = JSON.parse(evt.target.response);  
             $("#progressModal").modal("hide");  
             ResetUploadModal();  
            if (response.error) {  
              alert(response.message);  
              return;  
            }  
            populateTableData(response.data);  
          }  
          function populateTableData(data) {  
            if (data.length <= 0) return;  
              $("#tableBody").html('');  
            $.each(data, function (i, val) {  
              let tableRow = $("<tr></tr>");  
              let tablecells = `<td>${i + 1}</td>` +  
                `<td>${val.company}</td>` +  
                `<td>${val.category}</td>` +  
                `<td>${val.city}</td>` +  
                `<td>${val.date}</td>` +  
                `<td>${val.currency}</td>` +  
                `<td>${val.strAmount}</td>`;  
              tableRow.html(tablecells);  
              $("#tableBody").append(tableRow[0]);  
            });  
          }  
          function uploadFailed(evt) {  
            $("#progressModal").modal("hide");  
            ResetUploadModal();  
            alert("There was an error attempting to upload the file");  
          }  
          function uploadCanceled(evt) {  
            $("#progressModal").modal("hide");  
            ResetUploadModal();  
            alert("The upload has been canceled by the user or the browser dropped the connection")  
          }  
          function ResetUploadModal() {  
            document.getElementById("uploadFile").value = '';  
            document.getElementById("fileToUpload").value = null;  
            $("#progressContainer").hide();  
            $("#progress_bar").css("width", "-1%");  
          }  
        </script>  
      }  

The Controller should look like so:

 using System;  
 using System.Collections.Generic;  
 using System.Threading.Tasks;  
 using Microsoft.AspNetCore.Mvc;  
 using FileUpload.Models;  
 using System.IO;  
 using FileUpload.Hubs;  
 using Microsoft.AspNetCore.SignalR;  
 namespace FileUpload.Controllers  
  {  
    public class UploadController : Controller  
    {  
      private readonly IHubContext<BroadCastHub> hubContext;  
      public UploadController(IHubContext<BroadCastHub> _hubContext)  
      {  
        hubContext = _hubContext;  
      }  
      public IActionResult Index()  
      {  
        return View();  
      }  
      public async Task<JsonResult> UploadFile()  
      {  
        try  
        {  
          var counter = 0;  
          var currentCount = 0;  
          var data = new List<RecordItem>();  
          var postedFile = Request.Form.Files;  
          await Task.Delay(500);  
          currentCount++;  
          SendFeedBack(currentCount, counter);  
          if (postedFile.Count <= 0 || postedFile == null)  
            return Json(new { error = true, message = "Empty File was uploaded" });  
          if (postedFile[0] == null || postedFile[0].Length <= 0)  
          {  
            return Json(new { error = true, message = "Empty File was uploaded" });  
          }  
          await Task.Delay(500);  
          currentCount++;  
          SendFeedBack(currentCount, counter);  
          var fileInfo = new FileInfo(postedFile[0].FileName);  
          var extention = fileInfo.Extension;  
          if (extention.ToLower() != ".csv")  
          {  
            return Json(new { error = true, message = "invalid file format" });  
          }  
          using (StreamReader sr = new StreamReader(postedFile[0].OpenReadStream()))  
          {  
            await Task.Delay(500);  
            currentCount++;  
            SendFeedBack(currentCount, counter);  
            while (!sr.EndOfStream)  
            {  
              String Info = sr.ReadLine();  
              String[] Records;  
              if (Info.Contains('\"'))  
              {  
                var row = string.Empty;  
                var model = Info.Replace("\"", "#*").Split('#');  
                foreach (var item in model)  
                {  
                  var d = item.Replace("*,", ",");  
                  if (d.Contains("*"))  
                  {  
                    row += d.Replace("*", "").Replace(",", "");  
                  }  
                  else  
                  {  
                    row += d;  
                  }  
                }  
                Records = new String[row.Split(new char[] { ',' }).Length];  
                row.Split(new char[] { ',' }).CopyTo(Records, 0);  
              }  
              else  
              {  
                Records = new String[Info.Split(new char[] { ',' }).Length];  
                Info.Split(new char[] { ',' }).CopyTo(Records, 0);  
              }  
              var strAmount = Records[7].ToString().Trim();  
              decimal output;  
              if (string.IsNullOrEmpty(strAmount) || !decimal.TryParse(strAmount, out output)) continue;  
              var datafile = new RecordItem()  
              {  
                Company = Records[1].ToString().Trim(),  
                Category = Records[3].ToString().Trim(),  
                City = Records[4].ToString().Trim(),  
                Date = Records[6].ToString().Trim(),  
                Currency = Records[8].ToString().Trim(),  
                Amount = decimal.Parse(Records[7].ToString().Trim()),  
              };  
              data.Add(datafile);  
              counter++;  
              SendFeedBack(currentCount, counter);  
            }  
            sr.Close();  
            sr.Dispose();  
            await Task.Delay(500);  
             currentCount++;  
             SendFeedBack(currentCount, counter);  
           }  
           await Task.Delay(500);  
           currentCount++;  
           SendFeedBack(currentCount, counter);  
           return Json(new { error = false, data = data });  
         }  
         catch (Exception ex)  
         {  
           return Json(new  
           {  
             error = true,  
             message = ex.InnerException != null ?  
             ex.InnerException.Message : ex.Message  
           });  
         }  
       }  
       private async void SendFeedBack(int currentCount, int UploadCount)  
       {  
         var totalCount = 4;  
         var feedBackModel = new FeedbackModel()  
         {  
           currentCount = currentCount,  
           currentPercent = (currentCount * 100 / totalCount).ToString(),  
           UploadCount = UploadCount,  
         };  
         await hubContext.Clients.All.SendAsync("feedBack", feedBackModel);  
       }  
       public IActionResult Privacy()  
       {  
         return View();  
       }  
     }  
   }  

Build and run the solution. Select and upload the sample CSV file included in the source code.

You can download the source code from here.

Kindly drop your comments.

Thank you for your time.
Real Time File Upload with SignalR in Asp.Net Core Real Time File Upload with SignalR in Asp.Net Core Reviewed by Akintunde Toba on June 08, 2019 Rating: 5

No comments:

Home Ads

Powered by Blogger.