Monday 29 August 2016

Angularjs File Upload using WEB API






AngularFileUpload.js
/// <reference path="D:\MVCFileUpload\WebApiFileUpload\WebApiFileUpload\angular.js" />
var app = angular.module('myApp', [])
.controller('myController', function ($scope, $timeout, $interval, DocumentUploading) {

    $scope.count = 0;
    $scope.interval = 100;

    var increaseCounter = function () {
        if ($scope.count < 100) {
            $scope.count = $scope.count + 1;
        } else {
            $interval.cancel(increaseCounter);
            $scope.success = true;
        }
    }

    var handleFileSelect = function (evt) {
        var file = evt.currentTarget.files[0];
        $scope.selectFileforUpload = file;
        var reader = new FileReader();

        reader.onload = function (evt) {
            $scope.$apply(function ($scope) {
                $scope.myImage = evt.target.result;
            });
        };

        reader.readAsDataURL(file);
    };
    angular.element(document.querySelector('#fileInput')).on('change', handleFileSelect);

    $scope.uploadfile = function () {

        $interval(increaseCounter, $scope.interval);

        $scope.showbuffering = true;
        var xyz = $scope.selectFileforUpload;
        DocumentUploading.fact.UploadFileDocument(xyz, $scope.filename, "16341").then(function (response) {
            $scope.interval = 10;
            $interval(increaseCounter, $scope.interval);
            $scope.Message = response;
            if ($scope.Message != "OK") {
                $scope.count = 0;
                $interval.cancel(increaseCounter);
            }
            angular.element("input[type='file']").val(null);
            $timeout(function () {
                $scope.Message = "";
            }, 2000);
        }, function (response) {
            alert(response);
            $scope.count = 0;
            $interval.cancel(increaseCounter);
        })
    }
})

.factory('DocumentUploading', function ($http, $q) {
    return {
        fact: {
            UploadFileDocument: function (file,filename, EntryBy) {
                var deffered = $q.defer();
                var formdata = new FormData();
                formdata.append("file", file);              
                formdata.append("filename", filename);
                formdata.append("EntryBy", EntryBy);
                $http.post('api/Demo/UploadFile', formdata,
                       {
                           headers: { 'Content-type': undefined },
                           transformRequest: angular.identity
                       }).success(function (d) {
                           deffered.resolve(d);
                       }).error(function () {
                           deffered.reject('File Upload Fail !');
                       })
                return deffered.promise;
            }
        }
    }
})


FileUpload.html

<!DOCTYPE html>
<html ng-app="myApp">
<head>
    <title>File Uploading</title>
    <script src="scripts/jquery-1.9.1.js"></script>
    <script src="angular.js"></script>
    <script src="AngularFileUpload.js"></script>
    <script src="scripts/bootstrap.js"></script>
    <link href="Content/bootstrap.css" rel="stylesheet" />
    <link href="Content/bootstrap-theme.css" rel="stylesheet" />
    <link href="Content/font-awesome.css" rel="stylesheet" />
    <!--<link href="css/font-awesome.css" rel="stylesheet" />-->
    <!--<link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.6.3/css/font-awesome.min.css">-->
    <meta charset="utf-8" />
</head>
<body class="container" ng-controller="myController">
    <div class="row jumbotron" style="margin-top:40px">
        <div class="col-lg-offset-4 col-lg-4">
            <div class="row">
                <div class="thumbnail">
                    <img ng-src="{{myImage||'http://girlgameson.com/wp-content/themes/games/images/default.png'}}" id="showimage" class="thumbnail" alt="Image Not Available" />
                </div>
            </div>
            <div class="row">
                <div class="col-lg-4">
                    <label>Enter Name</label>
                </div>
                <div class="col-lg-8">
                    <div>
                        <input type="text" ng-model="filename" style="font-weight:bold" class="form-control" placeholder="Enter File Name" />
                    </div>
                </div>
            </div>
            <div class="row">
                <div style="position:relative;">
                    <a class='btn btn-primary' href='javascript:;'>
                        Choose File...
                        <input type="file" class="img-rounded" id="fileInput" style='position:absolute;z-index:2;top:0;left:0;filter: alpha(opacity=0);-ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=0)";opacity:0;background-color:transparent;color:transparent;' name="file_source" size="40" onchange='$("#upload-file-info").html($(this).val());' required>
                    </a>
                    <span class='label label-info' id="upload-file-info"></span>
                </div>
                <div style="margin-top:20px;">
                    <button class="btn btn-default" ng-click="uploadfile()">
                        <span class="icon-cloud-upload">&nbsp;Upload</span>
                    </button>
                </div>
            </div>
            <div class="row" style="margin-top:30px;">
                <div class="col-lg-6">
                    <div class="progress">
                        <div class="progress-bar"
                             role="progressbar"
                             aria-valuenow="0"
                             aria-valuemin="0"
                             aria-valuemax="100"
                             style="width:{{count}}%" align="center">
                            <strong>{{count}} %</strong>
                        </div>
                    </div>
                </div>
                <div class="row">
                    <div class="col-lg-4">
                        <strong>{{count}} %</strong>
                    </div>
                    <div class="col-lg-2" ng-init="success=false">                                     
                        <span class="text-success" ng-show="success"><i class="fa fa-check"></i></span>
                    </div>
                </div>

            </div>
        </div>
    </div>
</body>
</html>
DemoController

using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;

namespace WebApiFileUpload.Controllers
{
    public class DemoController : ApiController
    {
        [HttpPost]
        public async Task<HttpResponseMessage> UploadFile()
        {
            string Message = string.Empty;
            List<Documets> objlist = new List<Documets>();
            Documets obj = new Documets();
            List<string> messages = new List<string>();
            if (Request.Content.IsMimeMultipartContent())
            {
                //string path = ConfigurationManager.AppSettings["PODPath"].ToString();
                 string uploadPath = HttpContext.Current.Server.MapPath("~/Uploads");

                MyStreamProvider streamProvider = new MyStreamProvider(uploadPath);

                await Request.Content.ReadAsMultipartAsync(streamProvider);                
                obj.Description = streamProvider.FormData[0];
                obj.EntryBy = streamProvider.FormData[1];


                foreach (var file in streamProvider.FileData)
                {
                    FileInfo fi = new FileInfo(file.LocalFileName);

                    obj.filename = fi.Name;
                    obj.filetype = fi.Extension;
                    obj.filesize = fi.Length.ToString();
                    obj.filelocation = fi.DirectoryName;
                    obj.contenttype = file.Headers.ContentType.MediaType;
                    obj.FileGuid = fi.Name;
                    messages.Add("File uploaded as " + fi.FullName + " (" + fi.Length + " bytes)");
                }

                Message = DA_TaskDocument.InsertTaskDocument(obj);
                //return Request.CreateResponse(HttpStatusCode.OK);
                return Request.CreateResponse(Message);
            }
            else
            {
                HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.BadRequest, "Invalid Request!");
                throw new HttpResponseException(response);
            }
        }

        public class MyStreamProvider : MultipartFormDataStreamProvider
        {
            public MyStreamProvider(string uploadPath)
                : base(uploadPath)
            {

            }

            public override string GetLocalFileName(HttpContentHeaders headers)
            {
                string fileName = headers.ContentDisposition.FileName;
                if (string.IsNullOrWhiteSpace(fileName))
                {
                    fileName = Guid.NewGuid().ToString() + ".data";
                }
                return fileName.Replace("\"", string.Empty);
            }
        }
    }
}


DA_FileUpload

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace WebApiFileUpload
{
    public class DA_TaskDocument
    {
        public static string InsertTaskDocument(Documets obj)
        {
            string Message = string.Empty;
            try
            {
                string[] param = new string[] {                       
                         "@FileName",
                         "@ContentType",
                         "@FileGuid",
                         "@FilePath",
                         "@EntryBy",                     
                         "@Description"
                };
                string[] paramvalues = new string[] {                
                   obj.filename,
                   obj.contenttype,
                   obj.FileGuid,
                   obj.filelocation,
                   obj.EntryBy,                 
                   obj.Description
                };
                //usp_Ms_TaskDocument
                int i = SQL_Helper.Insert("Usp_savefile", param, paramvalues, "MyConnection");
                if (i > 0)
                {
                    Message = "OK";
                }
            }
            catch (Exception e)
            {
                return Message = e.Message;
            }
            return Message;
        }
    }
}

SQL Helper

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WebApiFileUpload
{
   public class SQL_Helper
    {
        public class GetParam
        {
            public string param { get; set; }
            public string paramvalue { get; set; }
            public GetParam(string _param, string _paramvalue)
            {
                this.param = _param;
                this.paramvalue = _paramvalue;
            }
        }

        public static DataTable Select(string procedure, string[] param, string[] paramvalue, string connection)
        {
            DataTable dt = new DataTable();
            try
            {
                if (param.Length == paramvalue.Length)
                {
                    List<GetParam> obj = new List<GetParam>();
                    for (int i = 0; i < param.Length; i++)
                    {
                        obj.Add(new GetParam(param[i], paramvalue[i]));
                    }

                    using (SqlConnection con = new SqlConnection(ConfigurationSettings.AppSettings[connection]))
                    {
                        using (SqlCommand cmd = new SqlCommand(procedure, con))
                        {
                            cmd.CommandType = CommandType.StoredProcedure;
                            for (int i = 0; i < obj.Count; i++)
                            {
                                cmd.Parameters.AddWithValue(obj[i].param, obj[i].paramvalue);
                            }
                            SqlDataAdapter da = new SqlDataAdapter(cmd);
                            da.Fill(dt);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                throw e;
            }
            return dt;
        }

        public static DataSet SelectFromDataset(string procedure, string[] param, string[] paramvalue, string connection)
        {
            DataSet ds = new DataSet();
            try
            {
                if (param.Length == paramvalue.Length)
                {
                    List<GetParam> obj = new List<GetParam>();
                    for (int i = 0; i < param.Length; i++)
                    {
                        obj.Add(new GetParam(param[i], paramvalue[i]));
                    }

                    using (SqlConnection con = new SqlConnection(ConfigurationSettings.AppSettings[connection]))
                    {
                        using (SqlCommand cmd = new SqlCommand(procedure, con))
                        {
                            cmd.CommandType = CommandType.StoredProcedure;
                            for (int i = 0; i < obj.Count; i++)
                            {
                                cmd.Parameters.AddWithValue(obj[i].param, obj[i].paramvalue);
                            }
                            SqlDataAdapter da = new SqlDataAdapter(cmd);
                            da.Fill(ds);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                throw e;
            }
            return ds;
        }

        public static int Insert(string procedure, string[] param, string[] paramvalue, string connection)
        {
            int j = 0;
            try
            {
                if (param.Length == paramvalue.Length)
                {
                    List<GetParam> obj = new List<GetParam>();
                    for (int i = 0; i < param.Length; i++)
                    {
                        obj.Add(new GetParam(param[i], paramvalue[i]));
                    }

                    DataTable dt = new DataTable();
                    using (SqlConnection con = new SqlConnection(ConfigurationSettings.AppSettings[connection]))
                    {
                        con.Open();
                        using (SqlCommand cmd = new SqlCommand(procedure, con))
                        {
                            cmd.CommandType = CommandType.StoredProcedure;
                            for (int i = 0; i < obj.Count; i++)
                            {
                                cmd.Parameters.AddWithValue(obj[i].param, obj[i].paramvalue);
                            }
                            j = cmd.ExecuteNonQuery();
                        }
                    }
                }
            }
            catch (Exception e)
            {
                throw e;
            }
            return j;
        }

        public static string ScalarReturn(string procedure, string[] param, string[] paramvalue,string outputparam ,string connection)
        {
            string Message = string.Empty;
            int j = 0;
            try
            {
                if (param.Length == paramvalue.Length)
                {
                    List<GetParam> obj = new List<GetParam>();
                    for (int i = 0; i < param.Length; i++)
                    {
                        obj.Add(new GetParam(param[i], paramvalue[i]));
                    }

                    DataTable dt = new DataTable();
                    using (SqlConnection con = new SqlConnection(ConfigurationSettings.AppSettings[connection]))
                    {
                        con.Open();
                        using (SqlCommand cmd = new SqlCommand(procedure, con))
                        {
                            cmd.CommandType = CommandType.StoredProcedure;
                            for (int i = 0; i < obj.Count; i++)
                            {
                                cmd.Parameters.AddWithValue(obj[i].param, obj[i].paramvalue);
                            }
                            cmd.Parameters.Add(outputparam, SqlDbType.VarChar, 30);
                            cmd.Parameters[outputparam].Direction = ParameterDirection.Output;
                            cmd.ExecuteNonQuery();
                            Message= cmd.Parameters[outputparam].Value.ToString();
                        }
                    }
                }
            }
            catch (Exception e)
            {
                return e.Message;
            }
            return Message;
        }
    }
}


public class Documets
    {
        public string documenttype { get; set; }
        public string companyID { get; set; }
        public string filename { get; set; }
        public string filesize { get; set; }
        public string filelocation { get; set; }
        public string filetype { get; set; }
        public string contenttype { get; set; }
        public string FileGuid { get; set; }
        public string Description { get; set; }
        public string EntryBy { get; set; }
        public string TaskID { get; set; }
    }


Procedure

CREATE PROC Usp_savefile(@FileName    VARCHAR(100) = NULL,
                         @ContentType VARCHAR(50) = NULL,
                         @FileGuid    VARCHAR(MAX) = NULL,
                         @FilePath    VARCHAR(100) = NULL,
                         @EntryBy     VARCHAR(6) = NULL,
                         @Description VARCHAR(MAX) = NULL,
                         @Message     VARCHAR(250) = NULL OUTPUT)
AS
  BEGIN
      INSERT INTO FileUpload
                  (FileName,
                   ContentType,
                   FileGuid,
                   FilePath,
                   EntryBy,
                   EntryDate,
                   Description)
      VALUES      ( @FileName,
                    @ContentType,
                    @FileGuid,
                    @FilePath,
                    @EntryBy,
                    Getdate(),
                    @Description )

      SET @Message = 'INSERTED'
  END