Thursday, 23 February 2017

Using Angularjs multiple file upload using jQuery Ajax in asp.net

n this article, I will show you how to upload image using Angularjs. The generic handler helps to upload multiple files using jQuery, user click the upload button, the jQuery Ajax call the server side UploadHandler.ashx. The HttpContext provides access to the individual files that have been uploaded by a client, save the image to the project image folder.
Step 1Create an asp.net mvc project and right click on the controller folder and create a new controller and name it as HomeController. Inside the HomeController copy and paste the following code.
public ActionResult Index()
        {
            return View();
        }
Step 2: Right click on the index view and create a razor view named as index. Copy and paste the following code.
<html xmlns="http://www.w3.org/1999/xhtml">
<head data-ng-app="UploadApp">
    <title>AngularJS Upload Images using File Upload Plugin</title>
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/danialfarid-angular-file-upload/12.2.13/ng-file-upload-shim.min.js" type="text/javascript"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/danialfarid-angular-file-upload/12.2.13/ng-file-upload.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        //injectangular file upload directives and services.
        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-height: 15px;
        }
 
        .progress {
            display: inline-block;
            width: 100px;
            border: 3px groove #CCC;
        }
 
            .progress div {
                font-size: smaller;
                background: #357ae8;
                width: 0;
            }
 
        .box {
            border: 1px solid #DED8D8;
            width: 500px;
            height: 325px;
            font-family: Arial;
        }
    </style>
</head>
<body ng-app="fileUpload" ng-controller="MyCtrl" class="box">
    <form name="myForm">
        <h3>AngularJS Upload Multiple Files</h3>
        Upload:
        <input type="file" ngf-select ng-model="picFile" name="file" multiple accept="image/*" ngf-max-size="2MB" required
            ngf-model-invalid="errorFile">
        <i ng-show="myForm.file.$error.required">*required</i><br>
        <i ng-show="myForm.file.$error.maxSize">File too large
{{errorFile.size / 1000000|number:1}}MB: max 2M</i>
        <br>
        <button ng-disabled="!myForm.$valid" ng-click="uploadPic(picFile)">Submit</button><br />
        <span class="progress" ng-show="picFile.progress >= 0">
            <div style="width: {{picFile.progress}}%"
                ng-bind="picFile.progress + '%'">
            </div>
        </span>
        <span ng-show="picFile.result">Upload Successful</span>
        <span class="err" ng-show="errorMsg">{{errorMsg}}</span>
    </form>
</body>
</html>
Step 3: Create a Generic Handler file in the application by the following steps. Right click on the project and select new item-- > Select Generic handler file and name it as UploadHandler.ashx. Copy and paste the following code on it,
        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("~/Images/"),fname);
                    file.SaveAs(fname);
                }
            }
            context.Response.ContentType = "text/plain";
            context.Response.Write("File Uploaded Successfully!");
        }
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    } 
Description: The following cdn jQuery Ajax file upload plugin’s should be registered to the page, ng-file-upload-shim.min.js and ng-file-upload.min.js. Here, we have set file upload restriction; it allows 2 mb files to upload with the angularjs file upload module.
Angularjs file upload example:

0 comments: