Introduction
The Angular-file-upload directive by nervgh is an awesome lightweight AngularJS directive that handles file upload for you and lets you upload files asynchronously to the server. This article will provide you with a basic understanding of how to upload files using this directive together with the .NET WebAPI service on a 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 that can be built afterwards around the angular-file-upload.
Background
From the Unix man page: "sftp is an interactive file transfer program, similar to ftp that does 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 sent 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
AngularJS Controller Code
- 'use strict';
-
- angular
- .module('app', ['angularFileUpload'])
- .controller('AppController', ['$scope', 'FileUploader', function($scope, FileUploader) {
-
-
- var uploader = $scope.uploader = new FileUploader({
- url: window.location.protocol + '//' + window.location.host +
- window.location.pathname + '/api/Upload/UploadFile'
- });
-
-
-
- uploader.filters.push({
- 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;
- }
- }
- });
-
- uploader.filters.push({
- 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;
- }
- }
- });
-
- uploader.filters.push({
- 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('onCompleteAll');
- };
-
- console.info('uploader', uploader);
- }]);
Web API Controller
- [System.Web.Http.HttpPost]
- 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)
- Directory.CreateDirectory(HttpContext.Current.Server.MapPath("~/UploadedDocuments"));
- var fileSavePath = Path.Combine(HttpContext.Current.Server.MapPath("~/UploadedDocuments"),
- httpPostedFile.FileName);
- httpPostedFile.SaveAs(fileSavePath);
-
- if (File.Exists(fileSavePath))
- {
-
- using (SftpClient sftpClient = new SftpClient(AppConfig.SftpServerIp,
- Convert.ToInt32(AppConfig.SftpServerPort),
- AppConfig.SftpServerUserName,
- AppConfig.SftpServerPassword))
- {
- sftpClient.Connect();
- if (!sftpClient.Exists(AppConfig.SftpPath + "UserID"))
- {
- sftpClient.CreateDirectory(AppConfig.SftpPath + "UserID");
- }
-
- Stream fin = File.OpenRead(fileSavePath);
- sftpClient.UploadFile(fin, AppConfig.SftpPath + "/" + httpPostedFile.FileName,
- true);
- fin.Close();
- sftpClient.Disconnect();
- }
- }
- }
- }
Points of Interest
1. extensionFilter is used to allow only PDF, Word and RTF documents.
2. The 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 the WebAPI, an UploadedDocuments folder is created to get the file into the webserver from the client.
5. Drag and drop is also implemented along with a default browse button.
For the complete source code, please see https://github.com/m-hassan-tariq/SFTPFileUploadUsingWebAPIandAngularJS