Upload file in Folder (Directory) and path in Database using AngularJS in ASP.Net MVC

Last Reply 9 months ago By dharmendr

Posted 10 months ago

Hi,

I have one table named as Form it has 3 fields

Id, Name and Resume

coming to my requirement is i need to save all records after clicking of submit button. I need to save Upload a file to Sever (folder) and name to database

Note: Upload file is not coming to controller code

could you please check my code and help me 

@{
    Layout = null;
}

<html ng-app="myApp">
<head>
    <title></title>
    <link href="//netdna.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" />
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.2-rc.1/css/select2.min.css" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.2-rc.1/js/select2.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.2-rc.1/js/select2.full.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.5/angular.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.8/angular.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.8/angular.min.js"></script>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/danialfarid-angular-file-upload/12.2.13/ng-file-upload.min.js"></script>
    <script src="~/scripts/dirpagination.js"></script>
    <script>
        var app = angular.module("myApp", ['ngFileUpload', 'angularUtils.directives.dirPagination']);
        app.controller("myCntrl", ['$scope', '$http', 'myService', function ($scope, $http, myService) {
            $scope.mahesh = false;
            $scope.UploadFiles = function (files) {
                $scope.SelectedFiles = files;
            };
            $scope.AddUpdateEmployee = function () {
                debugger;
                $scope.mahesh = $scope.mahesh ? false : true;
                var Country = {
                    Id: $scope.Id,
                    Name: $scope.Name,
                    Resume: $scope.SelectedFiles,
                };
                var getAction = $scope.Action;
                    var getData = myService.AddSt(Country);
                    getData.then(function (msg) {
                        ClearFields();
                        alert(msg.data);
                        $scope.msg = msg.data;
                    }, function (msg) {
                        //$("#alertModal").modal('show');
                        alert(msg.data);
                        $scope.msg = msg.data;
                    });
            }
            $scope.AddStateDiv = function () {
                debugger;
                $scope.mahesh = $scope.mahesh ? false : true;
                ClearFields();
                $scope.Action = "Add";
            }
        }]);
        app.service("myService", function ($http) {
           this.AddSt = function (employee) {
                var response = $http({
                    method: "post",
                    url: "/master/AddState",
                    data: JSON.stringify(employee),
                    dataType: "json"
                });
                return response;
            }
        });
    </script>
</head>
<body ng-controller="myCntrl">
    <div class="container">
        <div>
            <div id="wrapper" class="clearfix" ng-show="mahesh">
                <form name="userForm" novalidate>
                    <h4 class="modal-title" style="text-align:center;">{{Action}} State Details</h4>
                    <div class="form-horizontal">
                        <div class="form-row">
                            <div class="col-md-4">
                                <label for="COI_Name">Upload a file</label>
                                <input type="file" ngf-select="UploadFiles($files)" />
                            </div>
                            <div>
                                <div class="col-md-4">
                                    <label for="Name">Name</label>
                                    <input type="text" class="form-control" name="Name" ng-model="Name" placeholder="Enter  State Name" required />
                                </div>
                            </div>
                        </div>
                        <div></div>
                        <div class="form-group"></div>
                        <div class="form-group" style="width: 120%; text-align: center; padding: 10px;">
                            <div class="col-md-offset-2 col-md-5">
                                <p>
                                    <button class="btn btn-success btn-sm" ng-model="IsVisible" ng-click="AddUpdateEmployee()"><span class="glyphicon glyphicon-ok"></span>Submitt</button>
                                    <button class="btn btn-danger btn-sm" ng-click="close()"><span class="glyphicon glyphicon-remove"></span>Close</button>
                                </p>
                            </div>
                        </div>
                    </div>
                </form>
            </div>
            <button class="btn btn-success btn-sm " ng-click="AddStateDiv();" style="margin-left: 15px;">Add Country </button>
            <hr style="width: 550px;" />
        </div>
    </div>
</body>
</html>

 

 public string AddState(Form st)
        {
            if (st != null)
            {
                Form state = new Form();
                state.Id = st.Id;
                state.Name = st.Name;
                state.Resume = st.Resume;              
                db.Forms.Add(state);
                db.SaveChanges();
                return "State added Successfully";
            }
            else
            {
                return "Addition of state unsucessfull !";
            }
        }

 

 

Posted 9 months ago

Hi mahesh213,

Refer below code.

Controller

public class HomeController : Controller
{
    // GET: /Home/
    public ActionResult Index()
    {
        return View();
    }

    public string AddState()
    {
        Form st = JsonConvert.DeserializeObject<Form>(Request.Form["details"]);
        if (!string.IsNullOrEmpty(st.Name))
        {
            string fileName = "";
            for (int i = 0; i < Request.Files.Count; i++)
            {
                HttpPostedFileBase postedFile = Request.Files[i];
                if (Request.Browser.Browser.ToUpper() == "IE" || Request.Browser.Browser.ToUpper() == "INTERNETEXPLORER")
                {
                    string[] file = postedFile.FileName.Split(new char[] { '\\' });
                    fileName = file[file.Length - 1];
                }
                else
                {
                    fileName = postedFile.FileName;
                }
                postedFile.SaveAs(Path.Combine(Server.MapPath("~/App_Data/"), fileName));
            }

            Form state = new Form();
            state.Id = st.Id;
            state.Name = st.Name;
            state.Resume = fileName;
            db.Forms.Add(state);
            db.SaveChanges();
            return "State added Successfully";
        }
        else
        {
            return "Addition of state unsucessfull !";
        }
    }
}

public partial class Form
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Resume { get; set; }
}

View

<html ng-app="myApp" xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Index</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" />
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.2-rc.1/css/select2.min.css" />
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.2-rc.1/js/select2.min.js"></script>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.2-rc.1/js/select2.full.js"></script>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.8/angular.min.js"></script>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/danialfarid-angular-file-upload/12.2.13/ng-file-upload.min.js"></script>
    <script type="text/javascript" src="../../dirPagination.js"></script>
    <script type="text/javascript">
        var app = angular.module("myApp", ['ngFileUpload', 'angularUtils.directives.dirPagination']);
        app.controller("myCntrl", ['$scope', '$http', 'myService', function ($scope, $http, myService) {
            $scope.mahesh = false;
            $scope.UploadFiles = function (files) {
                $scope.SelectedFiles = files;
            };
            $scope.AddUpdateEmployee = function () {
                $scope.mahesh = $scope.mahesh ? false : true;
                var formData = new FormData();
                var files = $scope.SelectedFiles;
                if (files != undefined) {
                    for (var i = 0; i < files.length; i++) {
                        formData.append(files[i].name, files[i]);
                    }
                }
                var details = {};
                details.Id = 1; // Pass id as per your need.
                details.Name = $scope.Name;
                formData.append("details", JSON.stringify(details));

                var getAction = $scope.Action;

                var getData = myService.AddSt(formData);
                getData.then(function (msg) {
                    debugger
                    $scope.msg = msg;
                });
            }
            $scope.AddStateDiv = function () {
                $scope.mahesh = $scope.mahesh ? false : true;
                $scope.Action = "Add";
            }
        } ]);

        app.service("myService", function ($http) {
            this.AddSt = function (employee) {
                var response = $.ajax({
                    url: '/master/AddState',
                    type: "POST",
                    contentType: false,
                    processData: false,
                    data: employee
                });

                return response;
            }
        }); 
    </script>
</head>
<body ng-controller="myCntrl">
    <div class="container">
        <div>
            <div id="wrapper" class="clearfix" ng-show="mahesh">
                <form name="userForm" novalidate>
                <h4 class="modal-title" style="text-align: center;">
                    {{Action}} State Details</h4>
                <div class="form-horizontal">
                    <div class="form-row">
                        <div class="col-md-4">
                            <label for="COI_Name">
                                Upload a file</label>
                            <input type="file" ngf-select="UploadFiles($files)" />
                        </div>
                        <div>
                            <div class="col-md-4">
                                <label for="Name">
                                    Name</label>
                                <input type="text" class="form-control" name="Name" ng-model="Name" placeholder="Enter  State Name"
                                    required />
                            </div>
                        </div>
                    </div>
                    <div>
                    </div>
                    <div class="form-group">
                    </div>
                    <div class="form-group" style="width: 120%; text-align: center; padding: 10px;">
                        <div class="col-md-offset-2 col-md-5">
                            <p>
                                <button class="btn btn-success btn-sm" ng-model="IsVisible" ng-click="AddUpdateEmployee()">
                                    <span class="glyphicon glyphicon-ok"></span>Submitt</button>
                                <button class="btn btn-danger btn-sm" ng-click="close()">
                                    <span class="glyphicon glyphicon-remove"></span>Close</button>
                            </p>
                        </div>
                    </div>
                </div>
                </form>
            </div>
            <button class="btn btn-success btn-sm " ng-click="AddStateDiv();" style="margin-left: 15px;">
                Add Country
            </button>
            <hr style="width: 550px;" />
        </div>
    </div>
</body>
</html>

 


Posted 9 months ago
dharmendr says:
state.Resume = fileName;

Change the above line with the below.

state.Resume = "~/App_Data/" + fileName;

If you want to save complete address then change with below.

state.Resume = Path.Combine(Server.MapPath("~/App_Data/"), fileName);