Navigation

Sunday 23 April 2017

AngularJS - Upload File using file Handler.ashx


Html page


<div class="col-sm-9">
 <input type="file" id="FileUpload1" name="FileUpload1" ng-files="fngetFiles($files)" />   
 <button ng-click = "UploadFile ()">Upload</button>                               
</div>

--End to html page --- 

Add directive 'ngFiles' this will initialize when you select file.


var myApp = angular.module('myApp', []); 
myApp.directive('ngFiles', ['$parse', function ($parse) {
        function fn_link(scope, element, attrs) {
            var onChange = $parse(attrs.ngFiles);
            element.on('change', function (event) {
                onChange(scope, { $files: event.target.files });
            });
        };

        return {
            link: fn_link
        }
    }])


---End to directive-----

Add these functions to your controller.

$scope.UploadFile = function () {
         debugger;
         var fileUpload = $("#FileUpload1").get(0);
         var files = fileUpload.files;
         var test = new FormData();
         for (var i = 0; i < files.length; i++) {
             test.append(files[i].name, files[i]);
         }
         $.ajax({
             url: "UploadHandler.ashx?eid=" + sessionStorage.EmployeeId,
             type: "POST",
             contentType: false,
             processData: false,
             data: test,
             // dataType: "json",
             success: function (result) {
                 //alert(result);
             },
             error: function (err) {
                 //alert(err.statusText);
             }
         });
     }
$scope.fngetFiles = function (file) {
         debugger;
         var size = file[0].size;
         var MaxSize = 10 * 1024 * 1024
         if (MaxSize < size) {
             alert("File size should not be greater than 10Mb.");
             $('#FileUpload1').val("");
             return false;
         }
         var type = file[0].type;
         switch (type) {
             case 'application/vnd.openxmlformats-officedocument.wordprocessingml.document':
             case 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet':
             case 'application/pdf':
                 return true;
                 break;
             default:
   alert("Only PDF, Word and Excel are allowed. File size should not be greater than 10Mb");
                 $('#FileUpload1').val("");
                 return false;
         }

     } 

 -----End of controller----




Following is the code on handler['UploadHandler.ashx']. Whick will upload your files to server.


<%@ WebHandler Language="C#" Class="UploadHandler" %>

using System;
using System.Web;
using System.IO;
public class UploadHandler : IHttpHandler
{

    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "text/plain";

        string myFolder = context.Request.QueryString["eid"];
        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.Replace(" ","_");
                }
                bool folderExists = Directory.Exists(context.Server.MapPath("~/uploads/"+myFolder+"/"));
                if (!folderExists)
                    Directory.CreateDirectory(context.Server.MapPath("~/uploads/"+myFolder+"/"));

                fname = Path.Combine(context.Server.MapPath("~/uploads/"+myFolder+"/"), fname);
                file.SaveAs(fname);
            }
        }
        context.Response.ContentType = "text/plain";
        context.Response.Write("File Uploaded Successfully!");
    }
    public bool IsReusable
    {
        get
        {
            return false;
        }
    }


}

2 comments: