SFTP File upload using ASP.NET Web API and AngularJS

Uplaod files to SFTP using ASP.NET Web API and AngularJS upload plugin by nervgh with Bootstrap 3.0


Angular-file-upload directive by nervgh is an awesome lightweight AngularJS directive which handles file upload for you and lets you upload files asynchronously to the server. This post will give you basic understanding on how to upload files by using this directive together with .NET WebAPI service on SFTP server. For the purpose of this tutorial, I’ll keep everything as simple as possible since the focus here is on connecting AngularJS and async upload with a .NET WebAPI service and not on additional functionality which can be built afterwards around angular-file-upload.


From the unix man page: “sftp is an interactive file transfer program, similar to ftp, which performs all operations over an encrypted ssh transport”.
Why is SFTP better than FTP?
In FTP all data is passed back and forth between the client and server without the use of encryption. This makes it possible for an evesdropper to listen in and retrieve your confidential information including login details. With SFTP all the data is encrypted before it is sentsent across the network.

Using the code

A brief description of how to use the article or code. The class names, the methods and properties, any tricks or tips.

Html Code:

<html id="ng-app" ng-app="app">
    <title>Simple example</title>
    <link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/
     bootstrap.min.css" />
    <script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
    <script src="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
    <script src="http://code.angularjs.org/1.1.5/angular.min.js"></script>
    <script src="~/Scripts/angular-file-upload.js"></script>
    <script src="~/Scripts/controllers.js"></script>
        .my-drop-zone {
            border: dotted 3px lightgray;

        .nv-file-over {
            border: dotted 3px red;
        .another-file-over-class {
            border: dotted 3px green;

        html, body {
            height: 100%;
<body ng-controller="AppController" nv-file-drop="" uploader="uploader"
filters="queueLimit, customFilter">
    <div class="container">
        <div class="row">
            <div class="col-md-3">
                <h3>Select files</h3>
                <div ng-show="uploader.isHTML5">
                    <div nv-file-drop="" uploader="uploader">
                        <div nv-file-over="" uploader="uploader"
                            over-class="another-file-over-class" class="well my-drop-zone">
                            Another drop zone with its own settings
                <input type="file" nv-file-select="" uploader="uploader" />
            <div class="col-md-9" style="margin-bottom: 40px">
                <h3>Upload queue</h3>
                <p>Queue length: {{ uploader.queue.length }}</p>
                <table class="table">
                            <th width="50%">Name</th>
                            <th ng-show="uploader.isHTML5">Size</th>
                            <th ng-show="uploader.isHTML5">Progress</th>
                        <tr ng-repeat="item in uploader.queue">
                            <td><strong>{{ item.file.name }}</strong></td>
                            <td ng-show="uploader.isHTML5" nowrap>
                            {{ item.file.size/1024/1024|number:2 }} MB</td>
                            <td ng-show="uploader.isHTML5">
                                <div class="progress" style="margin-bottom: 0;">
                                    <div class="progress-bar" role="progressbar"
                                     ng-style="{ 'width': item.progress + '%' }"></div>
                            <td class="text-center">
                                <span ng-show="item.isSuccess"><i class="glyphicon glyphicon-ok">
                                <span ng-show="item.isCancel"><i class="glyphicon
                              <span ng-show="item.isError"><i class="glyphicon glyphicon-remove">
                            <td nowrap>
                                <button type="button" class="btn btn-success btn-xs"
                                 ng-click="item.upload()" ng-disabled="item.isReady ||
                                 item.isUploading || item.isSuccess">
                                    <span class="glyphicon glyphicon-upload"></span> Upload
                                <button type="button" class="btn btn-warning btn-xs"
                                 ng-click="item.cancel()" ng-disabled="!item.isUploading">
                                    <span class="glyphicon glyphicon-ban-circle"></span> Cancel
                                <button type="button" class="btn btn-danger btn-xs"
                                    <span class="glyphicon glyphicon-trash"></span> Remove
                        Queue progress:
                        <div class="progress" style="">
                            <div class="progress-bar" role="progressbar"
                             ng-style="{ 'width': uploader.progress + '%' }"></div>
                    <button type="button" class="btn btn-success btn-s"
                        <span class="glyphicon glyphicon-upload"></span> Upload all
                    <button type="button" class="btn btn-warning btn-s"
                     ng-click="uploader.cancelAll()" ng-disabled="!uploader.isUploading">
                        <span class="glyphicon glyphicon-ban-circle"></span> Cancel all
                    <button type="button" class="btn btn-danger btn-s"
                    ng-click="uploader.clearQueue()" ng-disabled="!uploader.queue.length">
                        <span class="glyphicon glyphicon-trash"></span> Remove all

AngularJS Controller Code

'use strict';

.module('app', ['angularFileUpload'])
.controller('AppController', ['$scope', 'FileUploader', function($scope, FileUploader) {
    // Uploader Plugin Code
    var uploader = $scope.uploader = new FileUploader({
        url: window.location.protocol + '//' + window.location.host +
             window.location.pathname + '/api/Upload/UploadFile'

    // FILTERS

        name: 'extensionFilter',
        fn: function (item, options) {
            var filename = item.name;
            var extension = filename.substring(filename.lastIndexOf('.') + 1).toLowerCase();
            if (extension == "pdf" || extension == "doc" || extension == "docx" ||
                extension == "rtf")
                return true;
            else {
                alert('Invalid file format. Please select a file with pdf/doc/docs or
                rtf format and try again.');
                return false;

        name: 'sizeFilter',
        fn: function (item, options) {
            var fileSize = item.size;
            fileSize = parseInt(fileSize) / (1024 * 1024);
            if (fileSize <= 5)
                return true;
            else {
                alert('Selected file exceeds the 5MB file size limit.
                       Please choose a new file and try again.');
                return false;

        name: 'itemResetFilter',
        fn: function (item, options) {
            if (this.queue.length < 5)
                return true;
            else {
                alert('You have exceeded the limit of uploading files.');
                return false;
    uploader.onWhenAddingFileFailed = function (item, filter, options) {
        console.info('onWhenAddingFileFailed', item, filter, options);
    uploader.onAfterAddingFile = function (fileItem) {
        alert('Files ready for upload.');

    uploader.onSuccessItem = function (fileItem, response, status, headers) {
        $scope.uploader.queue = [];
        $scope.uploader.progress = 0;
        alert('Selected file has been uploaded successfully.');
    uploader.onErrorItem = function (fileItem, response, status, headers) {
        alert('We were unable to upload your file. Please try again.');
    uploader.onCancelItem = function (fileItem, response, status, headers) {
        alert('File uploading has been cancelled.');

    uploader.onAfterAddingAll = function(addedFileItems) {
        console.info('onAfterAddingAll', addedFileItems);
    uploader.onBeforeUploadItem = function(item) {
        console.info('onBeforeUploadItem', item);
    uploader.onProgressItem = function(fileItem, progress) {
        console.info('onProgressItem', fileItem, progress);
    uploader.onProgressAll = function(progress) {
        console.info('onProgressAll', progress);
    uploader.onCompleteItem = function(fileItem, response, status, headers) {
        console.info('onCompleteItem', fileItem, response, status, headers);
    uploader.onCompleteAll = function() {

    console.info('uploader', uploader);

Web API Controller

public void UploadFile()
    if (HttpContext.Current.Request.Files.AllKeys.Any())
        var httpPostedFile = HttpContext.Current.Request.Files["file"];
  bool folderExists = Directory.Exists(HttpContext.Current.Server.MapPath("~/UploadedDocuments"));
        if (!folderExists)
        var fileSavePath = Path.Combine(HttpContext.Current.Server.MapPath("~/UploadedDocuments"),

        if (File.Exists(fileSavePath))
            //AppConfig is static class used as accessor for SFTP configurations from web.config
            using (SftpClient sftpClient = new SftpClient(AppConfig.SftpServerIp,
                if (!sftpClient.Exists(AppConfig.SftpPath + "UserID"))
                    sftpClient.CreateDirectory(AppConfig.SftpPath + "UserID");

                Stream fin = File.OpenRead(fileSavePath);
                sftpClient.UploadFile(fin, AppConfig.SftpPath + "/" + httpPostedFile.FileName,

Points of Interest

1. extensionFilter is used to allow only pdf, doc, docx and rtf documents

2. File size limit is also implemented by allowing file upto 5 MB

3. Number of files allowed in upload queue is also implemented by filter.

4. In WebAPI, UploadedDocuments folder is created to get file into webserver from client.
5. Drag and drop is also implemented along with default browse button.

For the complete source code, please see https://github.com/m-hassan-tariq/SFTPFileUploadUsingWebAPIandAngularJS


One thought on “SFTP File upload using ASP.NET Web API and AngularJS

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s