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

Codingvila
0

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 sometimes we have some requirements like to upload files, folders,s or images into a database, and for a better user experience obviously, we try to implement such kinds of requirements with a faster way and good user interface. In my case, I got the following requirements from the client-side.

1) Design a Web Page where users can upload files, folders, images.
2) User can select multiple files, folders, images.
3) display a progress bar that indicates the time required to upload selected files in form of a 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,s or images from file upload control is successfully Complete.

Implementation


To achieve this 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 an example for demonstration.

Here I will write a script that will validate the size of the 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 the above code then you can see here I implement validation for file upload and not allows files which is more than 1 MB.  

Now, after creating 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 the user selects 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 the name as UploadHandler. To Add a Generic Handler you can follow these 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 the name of your handler.

Step6: Done.
Generic-Handler
Generic Handler
Add Generic Handler
Add-Generic-Handler

Now, we will write the following code in created Generic Handler UploadHandler.ashx
If You working with C# Then please follow the code described 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 the code described 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 explains 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 the size of the file. I hope this article helps you, if you have any query then please you can leave your comments in the comment box thank you.

Post a Comment

0 Comments

Thank you for your valuable time, to read this article, If you like this article, please share this article and post your valuable comments.

Once, you post your comment, we will review your posted comment and publish it. It may take a time around 24 business working hours.

Sometimes I not able to give detailed level explanation for your questions or comments, if you want detailed explanation, your can mansion your contact email id along with your question or you can do select given checkbox "Notify me" the time of write comment. So we can drop mail to you.

If you have any questions regarding this article/blog you can contact us on info.codingvila@gmail.com

Post a Comment
To Top