Upload file in Folder (Directory) and Path in Database on Button Click using AngularJS in ASP.Net MVC

Last Reply 8 days ago By dharmendr

Posted 10 days ago

Hi,

I have 2 tables on database after uploading of file i need to display values like below

Orders

.................

OrderId OrderName Resume

1 aaa F:\Upload Files\Upload Files\App_Data\mahesh.docx

where App_Data is the folder name and mahesh.docx is the file name

Items

.............

Id Name OrderId

1 mahesh 1

2 mahesh1 1

3 mahesh2 2

i need to upload a file(whatever it may be word,pdf,image,.xls,.csv) after that finally after clicking of save button in i need to save uploaded file to folder and file location to database

@{
    Layout = null;
}
<html>
<head>
    <title>Index</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js"></script>
    <script src="~/scripts/dirpagination.js"></script>
    <script type="text/javascript">
        var app = angular.module('MyApp', ['angularUtils.directives.dirPagination'])
           app.controller('MyController', function ($scope, $http, $window) {
            $scope.invoice = false;
            $scope.hide = false;
            $scope.ShowHide = function () {
                //If DIV is visible it will be hidden and vice versa.
                $scope.invoice = $scope.invoice ? false : true;
            }
            $scope.Customers = [];
            $scope.Add = function () {
                //Add the new item to the Array.
                var customer = {};
                customer.Name = $scope.Name;
                $scope.Customers.push(customer);
                //Clear the TextBoxes.
                $scope.Name = "";
            };

            $scope.Save = function () {
                debugger
                var orders = {};
                orders.OrderId = $scope.OrderId;
                orders.OrderName = $scope.OrderName;
                orders.resume = $scope.resume;
                var details = new Array();
                for (var i = 0; i < $scope.Customers.length; i++) {
                    var detail = {};
                    detail.Id = $scope.Customers[i].Id;
                    detail.Name = $scope.Customers[i].Name;                   
                    details.push(detail);
                }
                orders.details = details;

                $http({
                    method: "Post",
                    url: "/dynamicaalyAddRemove/SaveOrder",
                    dataType: 'json',
                    headers: { "Content-Type": "application/json" },
                    data: '{orders: ' + JSON.stringify(orders) + '}'
                }).success(function (data) {
                    alert(data);
                    $scope.Customers = [];
                    $scope.refresh();

                }).error(function (err) {
                    $scope.Message = err.Message;
                })
            };
        });
    </script>
</head>
<body>
    <div ng-app="MyApp" ng-controller="MyController">
        <div>
            <div class="row">
                <div class="col-md-12">
                    <div class="panel panel-default">
                        <table class="table table-condensed">
                            <tr class="active">
                                <td>Order Name</td>
                                <td><input type="text" id="orderName" class="form-control" name="name" ng-model="OrderName" /></td>
                              <td>Upload File</td>
                                <td><input type="file" ng-model="resume" /></td>                                
                            </tr>
                        </table>
                    </div>
                </div>
            </div>
            <table cellpadding="0" cellspacing="0">
                <tr>
                    <th>Name</th>
                    <th>&nbsp;</th>
                </tr>
                <tbody ng-repeat="m in Customers">
                    <tr>
                        <td ng-show="hide">{{m.Id}}</td>
                        <td><input type="text" class="form-control" ng-model="m.Name" /></td>
                    </tr>
                </tbody>
                <tfoot>
                    <tr>
                        <td><input type="text" ng-model="Name" /></td>
                        <td><input type="button" ng-click="Add()" value="Add" /></td>
                    </tr>
                </tfoot>
            </table>
            <div style="padding: 10px 0;">
                <input id="submit" type="button" value="Save" name="add" ng-click="Save()" class="btn btn-success" />
            </div>
        </div>
    </div>
    <button class="btn btn-success btn-sm " ng-click="ShowHide();" style="margin-left: 15px;">Add Order</button>
</body>
</html>

 

You are viewing reply posted by: dharmendr 8 days ago.
Posted 8 days ago Modified on 8 days ago

Hi mahesh213,

Check this example. Now please take its reference and correct your code.

For upload file i am using ngf-select directive whic is explained in the below article.

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

Then to send the Uploaded file to Controller i have used FormData object with jQuery AJAX.

I have send the order details as JSON string to the Controller and then from Request object convert the JSON string to Order1 object using Newtonsoft dll.

For convert JSON string refer below link.

How to read JSON string into DataTable and Class object using C# .Net

Model 

public class Order1
{
    public int OrderId { get; set; }
    public string OrderName { get; set; }
    public string Resume { get; set; }
    public List<Item> details { get; set; }
}

public partial class Item
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int OrderId { get; set; }
}

Controller

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

    [HttpPost]
    public ActionResult SaveOrder()
    {
        string fileName;
        string result = "Error! Order Is Not Complete!";
        // Get uploaded files from Request object.
        if (Request.Files.Count > 0)
        {
            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;
                }
                fileName = Path.Combine(Server.MapPath("~/App_Data/"), fileName);
                postedFile.SaveAs(fileName);
            }
        }

        // Get Order details from Request object.
        Order1 orders = JsonConvert.DeserializeObject<Order1>(Request.Form["orders"]);
        // Do other task.
        Order order = new Order();
        order.OrderName = orders.OrderName;
        order.Resume = fileName;
        db.Orders.Add(order);
        db.SaveChanges();
        int orderId = order.OrderId;
        foreach (var detail in orders.details)
        {
            Item item = new Item();
            item.Name = detail.Name;
            item.OrderId = orderId;
            db.Items.Add(item);
            db.SaveChanges();
        }
        result = "Success! Order Is Complete!";
        return Json(result, JsonRequestBehavior.AllowGet);
    }
}

View

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/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://ajax.googleapis.com/ajax/libs/angularjs/1.3.9/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 type="text/javascript">
    var app = angular.module('MyApp', ['ngFileUpload'])
    app.controller('MyController', function ($scope, Upload, $http, $window) {
        $scope.UploadFiles = function (files) {
            $scope.SelectedFiles = files;
        };
        $scope.hide = false;
        $scope.ShowHide = function () { }
        $scope.Customers = [];
        $scope.Add = function () {
            var customer = {};
            customer.Name = $scope.Name;
            $scope.Customers.push(customer);
            $scope.Name = "";
        };

        $scope.Save = function () {
            var orders = {};
            orders.OrderName = $scope.OrderName;
            var details = new Array();
            for (var i = 0; i < $scope.Customers.length; i++) {
                var detail = {};
                detail.Name = $scope.Customers[i].Name;
                details.push(detail);
            }
            orders.details = details;

            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]);
                }
            }
            formData.append("orders", JSON.stringify(orders));

            $.ajax({
                url: '/Home/SaveOrder',
                type: "POST",
                contentType: false,
                processData: false,
                data: formData,
                success: function (result) {
                    $scope.Customers = [];
                    $scope.refresh();
                },
                error: function (err) {
                    $scope.Message = err.Message;
                }
            });
        };
    });
</script>
<div ng-app="MyApp" ng-controller="MyController">
    <div>
        <div class="row">
            <div class="col-md-12">
                <div class="panel panel-default">
                    <table class="table table-condensed">
                        <tr class="active">
                            <td>Order Name</td>
                            <td><input type="text" id="orderName" class="form-control" name="name" ng-model="OrderName" /></td>
                            <td>Upload File</td>
                            <td><input type="file" ngf-select="UploadFiles($files)" /></td>
                        </tr>
                    </table>
                </div>
            </div>
        </div>
        <table cellpadding="0" cellspacing="0">
            <tr>
                <th>Name</th>
                <th>&nbsp;</th>
            </tr>
            <tbody ng-repeat="m in Customers">
                <tr>
                    <td ng-show="hide">{{m.Id}}</td>
                    <td><input type="text" class="form-control" ng-model="m.Name" /></td>
                </tr>
            </tbody>
            <tfoot>
                <tr>
                    <td><input type="text" ng-model="Name" /></td>
                    <td><input type="button" ng-click="Add()" value="Add" /></td>
                </tr>
            </tfoot>
        </table>
        <div style="padding: 10px 0;">
            <input id="submit" type="button" value="Save" name="add" ng-click="Save()" class="btn btn-success" />
        </div>
    </div>
</div>
<button class="btn btn-success btn-sm " ng-click="ShowHide();" style="margin-left: 15px;">Add Order</button>

Screenshot

Form Data

Values In Controller