AngularJS File Upload in ASP.NET using C# and VB.NET

watch_later Sunday, November 18, 2018

Introduction


In this article i am going to explain how to upload multiple images and files with jquery uploading progress bar using AngularJs in asp.net c# and vb.net. In my previous articles i explained MVC Angular CRUD Operation Using WEB API 2 With Stored Procedure and today with this article i will show how you can upload multiple files and images using angular in Asp.net.

Requirement


While we working with any web application sometime we have some requirement like to upload files, folder or images into database, and for better user experience obviously we try to implement such kind of requirement with faster way and good user interface. In my case i got following requirement from client side.

1) Design Web Page where user can upload files, folders, images.
2) User can select multiple files, folders, images.
3) display progress bar that indicate time required to upload selected files in form of percentage.
5) Add validation for file upload.
6) File/Image size should be 1 MB only, and allow only 1 MB files 
4) Show message when all the selected files, folder or images from file upload control is successfully Complete.

Implementation


To achieve these requirement we will use angular and i will explain to you how we can create multiple file upload control and for that here i am going to create example for demonstration.
Here i will write script that will validate a size of file and also inject angular file upload directives and services.
<script type="text/javascript">
    var app = angular.module('fileUpload', ['ngFileUpload']);
    app.controller('MyCtrl', ['$scope''Upload''$timeout'function ($scope, Upload, $timeout) {
        $scope.uploadPic = function (file) {
            file.upload = Upload.upload({
                url: 'UploadHandler.ashx',
                data: { file: file }
            });
 
            file.upload.then(function (response) {
                $timeout(function () {
                    file.result = response.data;
                });
            }, function (response) {
                if (response.status > 0)
                    $scope.errorMsg = response.status + ': ' + response.data;
            }, function (evt) {
                file.progress = Math.min(100, parseInt(100.0 * evt.loaded / evt.total));
            });
        }
    }]);
</script>
If you analyzed above code then you can see here i implement validation for file upload and not allows files witch is more then 1 MB.  
Now, after create this script you also need to link your script file of angular.min.js, ng-file-upload-shim.min.js and ng-file-upload.min.js just after <head> tag of your page something like: 
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js"></script>
<script src="scripts/ng-file-upload-shim.min.js" type="text/javascript"></script>
<script src="scripts/ng-file-upload.min.js" type="text/javascript"></script>
Now You can see the full html markup of our web page.

HTML

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head data-ng-app="UploadApp">
<title>AngularJS File Upload Example in Asp.Net</title>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js"></script>
<script src="scripts/ng-file-upload-shim.min.js" type="text/javascript"></script>
<script src="scripts/ng-file-upload.min.js" type="text/javascript"></script>
<script type="text/javascript">
    var app = angular.module('fileUpload', ['ngFileUpload']);
    app.controller('MyCtrl', ['$scope''Upload''$timeout'function ($scope, Upload, $timeout) {
        $scope.uploadPic = function (file) {
            file.upload = Upload.upload({
                url: 'UploadHandler.ashx',
                data: { file: file }
            });
 
            file.upload.then(function (response) {
                $timeout(function () {
                    file.result = response.data;
                });
            }, function (response) {
                if (response.status > 0)
                    $scope.errorMsg = response.status + ': ' + response.data;
            }, function (evt) {
                // Math.min is to fix IE which reports 200% sometimes
                file.progress = Math.min(100, parseInt(100.0 * evt.loaded / evt.total));
            });
        }
    }]);
</script>
<style type="text/css">
form .progress {
line-height15px;
}
 
.progress {
  width100%;
  background-color#ddd;
}
.progress div {
  width1%;
  height30px;
  background-color#223c88;
}
 
.upload-btn-wrapper {
  positionrelative;
  overflowhidden;
  displayinline-block;
}
 
.btn {
  border2px solid gray;
  color#fff;
  background-color#223c88;;
  padding8px 20px;
  border-radius8px;
  font-size20px;
  font-weightbold;
}
 
.upload-btn-wrapper input[type=file] {
  font-size100px;
  positionabsolute;
  left0;
  top0;
  opacity0;
  
}
 
button {
    background-color#4CAF50/* Green */
    border-radius8px;
    bordernone;
    colorwhite;
    padding8px 20px;
    text-aligncenter;
    text-decorationnone;
    displayinline-block;
    font-size16px;
}
</style>
</head>
<body ng-app="fileUpload" ng-controller="MyCtrl">
<form name="myForm">
<h3>AngularJS File Upload Example in Asp.Net</h3>
<div class="upload-btn-wrapper">
  <button class="btn">Upload a file</button>
  <input type="file" ngf-select ng-model="picFile" name="file" multiple accept="image/*" ngf-max-size="2MB" required
ngf-model-invalid="errorFile" />
</div>
<div>
<i ng-show="myForm.file.$error.required">Please select any files/images.</i><br>
<i style="colorred" ng-show="myForm.file.$error.maxSize">File too large
{{errorFile.size / 1000000|number:1}}MB: Max 1MB</i>
</div>
<br>
<div>
<button ng-disabled="!myForm.$valid" ng-click="uploadPic(picFile)">Submit</button>
</div>
<br>
<div style="background-color#f1f1f1!important">
<span style="color#fff!important" class="progress" ng-show="picFile.progress >= 0">
<div  style="width:{{picFile.progress}}%"
ng-bind="picFile.progress + '%'"></div>
</span>
</div >
<span style="color:#4CAF50!important" ng-show="picFile.result">Your Upload Successful</span>
<span style="color:Red" class="err" ng-show="errorMsg">{{errorMsg}}</span>
</form>
</body>
</html>
If you analyzed above code then we also used AngulerJs progress bar, when user select any files/image and submit at that progress bar appear on the screen and shows how much files/images are saved in form of percentage where 100% indicate all the selected files/images saved successfully.
Now, this is the time to add Generic Handler in our project, and we will give name as UploadHandler. To Add Generic Handler you can follow this steps.

Step1: Press Mouse Right Click on Name of Your Project.
Step2: Select Add.
Step3: Select Add New Item.
Step4: Select Generic Handler.
Step5: Give a name of your handler.
Step6: Done.
Generic-Handler
Generic Handler
Add Generic Handler
Add-Generic-Handler

Now, we will write following code in created Generic Handler UploadHandler.ashx
If You working with C# Then please follow code described as below.

C#

<%@ WebHandler Language="C#" Class="UploadHandler" %>
 
using System;
using System.Web;
using System.IO;
 
public class UploadHandler : IHttpHandler {
    
    public void ProcessRequest (HttpContext context) {
        if (context.Request.Files.Count > 0)
        {
            HttpFileCollection files = context.Request.Files;
            for (int i = 0; i < files.Count; i++)
            {
                HttpPostedFile file = files[i];
                string fname;
                if (HttpContext.Current.Request.Browser.Browser.ToUpper() == "IE" || HttpContext.Current.Request.Browser.Browser.ToUpper() == "INTERNETEXPLORER")
                {
                    string[] testfiles = file.FileName.Split(new char[] { '\\' });
                    fname = testfiles[testfiles.Length - 1];
                }
                else
                {
                    fname = file.FileName;
                }
                fname = Path.Combine(context.Server.MapPath("~/uploads/"), fname);
                file.SaveAs(fname);
            }
        }
    }
 
    public bool IsReusable 
    {
        get { return false;}
    }
}
If You working with VB.Net Then please follow code described as below.

Vb.Net

<%@ WebHandler Language="VB" Class="Handler" %>
 
Imports System.Web
Imports System.IO
 
Public Class Handler : Implements IHttpHandler
 
    Public Sub ProcessRequest(ByVal context As HttpContextImplements IHttpHandler.ProcessRequest
        If context.Request.Files.Count > 0 Then
            Dim files As HttpFileCollection = context.Request.Files
            For i As Integer = 0 To files.Count - 1
                Dim file As HttpPostedFile = files(i)
                Dim fname As String
                If HttpContext.Current.Request.Browser.Browser.ToUpper() = "IE" OrElse HttpContext.Current.Request.Browser.Browser.ToUpper() = "INTERNETEXPLORER" Then
                    Dim testfiles As String() = file.FileName.Split(New Char() {"\"c})
                    fname = testfiles(testfiles.Length - 1)
                Else
                    fname = file.FileName
                End If
                fname = Path.Combine(context.Server.MapPath("~/uploads/"), fname)
                file.SaveAs(fname)
            Next
        End If
        context.Response.ContentType = "text/plain"
        context.Response.Write("File Uploaded Successfully!")
    End Sub
 
    Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
        Get
            Return False
        End Get
    End Property
End Class

Output

AngularJS Select File
AngularJS Select File
AngularJS File Upload Validation
AngularJS File Upload Validation
AngularJS File Upload Successful
AngularJS File Upload Successful

Summary


This article explain how you can upload multiple images and files with jquery uploading progress bar using AngularJs in asp.net c# and vb.net, and also explains how you can validate size of file. I hope this article helps you, if you have any query then please you can leave your comments in comment box thank you.

Codingvila provides articles and blogs on web and software development for beginners as well as free Academic projects for final year students in Asp.Net, MVC, C#, Vb.Net, SQL Server, Angular Js, Android, PHP, Java, Python, Desktop Software Application and etc.



sentiment_satisfied Emoticon