Wednesday, 4 July 2018

Multiple File Upload example in AngularJS Using Web API

In this article I am going to share with you a simple example on how to upload multiple files in AngularJS and Asp.Net Web API.

Every new version of AngularJS looks promising and it’s opening new opportunities for frontend developers. If you are working on Single Page Applications using Angular, then I am sure you will find this article and its example, very useful.



A Web API Controller for a Simple File Upload Procedure – C# and Vb.Net


using System;
using System.Net.Http;
using System.Web.Http;

using System.IO;

namespace FileUpload
{
    public class FileUploadController : ApiController
    {
        [HttpPost()]
        public string UploadFiles()
        {
            int iUploadedCnt = 0;

            // DEFINE THE PATH WHERE WE WANT TO SAVE THE FILES.
            string sPath = "";
            sPath = System.Web.Hosting.HostingEnvironment.MapPath("~/locker/");

            System.Web.HttpFileCollection hfc = System.Web.HttpContext.Current.Request.Files;

            // CHECK THE FILE COUNT.
            for (int iCnt = 0; iCnt <= hfc.Count - 1; iCnt++)
            {
                System.Web.HttpPostedFile hpf = hfc[iCnt];

                if (hpf.ContentLength > 0)
                {
                    // CHECK IF THE SELECTED FILE(S) ALREADY EXISTS IN FOLDER. (AVOID DUPLICATE)
                    if (!File.Exists(sPath + Path.GetFileName(hpf.FileName)))
                    {
                        // SAVE THE FILES IN THE FOLDER.
                        hpf.SaveAs(sPath + Path.GetFileName(hpf.FileName));
                        iUploadedCnt = iUploadedCnt + 1;
                    }
                }
            }

            // RETURN A MESSAGE (OPTIONAL).
            if (iUploadedCnt > 0) {
                return iUploadedCnt + " Files Uploaded Successfully";
            }
            else {
                return "Upload Failed";
            }
        }
    }
}


Once you have created the API, it’s time to create the web page, using few AngularJS directives.


AngularJS View

<!DOCTYPE html>
<html>
<head>
  <title>File Upload Example in AngularJS</title>
  <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.min.js"></script>
</head>

<body ng-app="fupApp">

    <div ng-controller="fupController">
        <input type="file" id="file" name="file" multiple
            onchange="angular.element(this).scope().getFileDetails(this)" />

        <input type="button" ng-click="uploadFiles()" value="Upload" />

        <!--ADD A PROGRESS BAR ELEMENT.-->
        <p><progress id="pro" value="0"></progress></p>
    </div>

</body>

The Controller and the Scope

<script>
    var myApp = angular.module('fupApp', []);

    myApp.controller('fupController', function ($scope) {

        // GET THE FILE INFORMATION.
        $scope.getFileDetails = function (e) {

            $scope.files = [];
            $scope.$apply(function () {

                // STORE THE FILE OBJECT IN AN ARRAY.
                for (var i = 0; i < e.files.length; i++) {
                    $scope.files.push(e.files[i])
                }

            });
        };

        // NOW UPLOAD THE FILES.
        $scope.uploadFiles = function () {

            //FILL FormData WITH FILE DETAILS.
            var data = new FormData();

            for (var i in $scope.files) {
                data.append("uploadedFile", $scope.files[i]);
            }

            // ADD LISTENERS.
            var objXhr = new XMLHttpRequest();
            objXhr.addEventListener("progress", updateProgress, false);
            objXhr.addEventListener("load", transferComplete, false);

            // SEND FILE DETAILS TO THE API.
            objXhr.open("POST", "/api/fileupload/");
            objXhr.send(data);
        }

        // UPDATE PROGRESS BAR.
        function updateProgress(e) {
            if (e.lengthComputable) {
                document.getElementById('pro').setAttribute('value', e.loaded);
                document.getElementById('pro').setAttribute('max', e.total);
            }
        }

        // CONFIRMATION.
        function transferComplete(e) {
            alert("Files uploaded successfully.");
        }
    });
</script>

No comments:

Post a Comment