locked
Angularjs with api - can't get file data in api controller throw angularjs ? RRS feed

  • Question

  • User-1846805900 posted

    Hi

    i try here to save form into database throw web api with angularjs - i can get all data but i can't get any data from file upload input ?! i need to get data from it to let me save it and upload it ?

        <form method="post" ng-submit="saveInvoice(); invoice={}">
            <table class="table table-striped table-bordered" dir="rtl">
                <tr>
                    <th class="text-center">العميل</th>
                    <th class="text-center">تاريخ الفاتورة</th>
                    <th class="text-center">الإجمالى</th>
                    <th>ملف</th>
                    <th></th>
                </tr>
                <tr>
                    <td align="center" style="vertical-align:middle;">
                        <div>
                            @(Html.Kendo()
                                  .AutoComplete()
                                  .Name("Customers").DataTextField("ContactName")
                                  .Events(events => events.Select("CustomerSelect"))
                                  .MinLength(1).HtmlAttributes(new { style = "width:450px; font-weight:bold", ng_model = "invoice.ContactName" })
                                  .Placeholder("إكتب جزء من إسم العميل").Filter("contains")
                                  .Delay(1).DataSource(source =>
                                  {
                                      source.Custom().ServerFiltering(true).ServerPaging(true).Type("aspnetmvc-ajax")
                                            .Transport(transport =>
                                            {
                                                transport.Read("Virtualization_Customer_Read", "Home");
                                            })
                                            .Schema(schema =>
                                            {
                                                schema.Data("Data").Total("Total");
                                            });
                                  })
                                  .Virtual(v => v.ItemHeight(26).ValueMapper("cusvalueMapper"))
                            )
    
                        </div>
                    </td>
                    <td style="display:none;">
                        @Html.TextBox("CustomerID", null, new { ng_model = "invoice.CustomerID" })
                    </td>
                    <td align="center" style="vertical-align:middle;">
                        @(Html.Kendo()
                              .DatePicker()
                              .Format("yyyy-MM-dd")
                              .Name("OrderDate")
                              .HtmlAttributes(new { style = "width:150px; font-weight:bold; text-align:center", ng_model = "invoice.OrderDate" })
                        )
                    </td>
                    <td align="center" style="vertical-align:middle; width:175px; font-weight:bold">
                        {{calculate_grand_total() | currency}}
                        @Html.TextBox("Total", null, new { ng_model = "invoice.Total = calculate_grand_total()", style = "display:none;" })
                    </td>
                    <td>
                        <input type="file" name="File" ng-model="invoice.File" />
                    </td>
                    <td align="center" style="vertical-align:middle;">
                        <input ng-disabled="invoice.CustomerID == '' || invoice.OrderDate == null || invoice.Total == 0.00" type="submit" name="submitbtn" value="حفظ الفاتورة" class="btn btn-success" style="font-weight:bold;" />
                    </td>
                </tr>
                <tr>
                    <td colspan="6" class="text-center" style="color:red; font-weight:bold;">
                        <div ng-show="invoice.CompanyName == ''">يجب إختيار أحد العملاء</div>
                        <div ng-show="invoice.OrderDate  == ''">يجب إدخال تاريخ الفاتورة</div>
                    </td>
                </tr>
            </table>
        </form>

    as you can see it set input here as:

                    <td>
                        <input type="file" name="File" ng-model="invoice.File" />
                    </td>

    but i can't get any thing about it in my controller - i got all other data 

    so please can i know what is problem here and how can i get file data here ?

    Tuesday, June 16, 2015 11:12 AM

Answers

All replies

  • User2024324573 posted

    Follow this example in fiddle how to upload file using Angular JS:

    http://jsfiddle.net/JeJenny/ZG9re/

    In your code there is missing part for uploading the file.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, June 17, 2015 12:17 AM
  • User438962230 posted

    @a.amin,

    You have to use your own directive, Angular can't bind file data automatically, see this thread talking about the same problem:

    ng-model for <input type=“file”/>

    Wednesday, June 17, 2015 6:23 AM
  • User-1846805900 posted

    Follow this example in fiddle how to upload file using Angular JS:

    http://jsfiddle.net/JeJenny/ZG9re/

    In your code there is missing part for uploading the file.

    Thanks a lot Mostafa - it's worked now - but i can't empty the input of file uploader after upload file i use it as :

    app.directive('fileModel', ['$parse', function ($parse) {
        return {
            restrict: 'A',
            link: function (scope, element, attrs) {
                var model = $parse(attrs.fileModel);
                var modelSetter = model.assign;
    
                element.bind('change', function () {
                    scope.$apply(function () {
                        modelSetter(scope, element[0].files[0]);
                    });
                });
            }
        };
    }]);
    
    app.service('fileUpload', ['$http', function ($http, $scope) {
        this.uploadFileToUrl = function (file, uploadUrl) {
            var fd = new FormData();
            fd.append('file', file);
            $http.post(uploadUrl, fd, {
                transformRequest: angular.identity,
                headers: { 'Content-Type': undefined }
            })
            .success(function (data) {
                alertify.set('notifier', 'position', 'top-left');
                alertify.success('تم حفظ الصنف برقم ' + data.id, 5);
    
                // i try here to set file = null - but nothing 
            })
            .error(function () {
                // called asynchronously if an error occurs
                // or server returns response with an error status.
                alertify.set('notifier', 'position', 'top-right');
                alertify.error('يوجد خطأ', 5);
                return;
            });
        }
    }]);
    
        $scope.saveInvoice = function (data) {
            $http.post("/api/customerService/SaveInvoice", $scope.invoice)
    
            .success(function (data) {
                var file = $scope.File;
                var uploadUrl = "/api/customerService/PostFile?id=" + data.ID;
                fileUpload.uploadFileToUrl(file, uploadUrl);
    
                $scope.tax = 0.00;
                $scope.PercentageDiscount = 0.00;
                $scope.MoneyDiscount = 0.00;
                $scope.invoice = { ContactName: "عميل نقدى" };
    
                // i try here to set $scope.File = null - but nothing 
    
                $scope.orders = [];
                $scope.lastID = data.ID;
    
                var today = new Date().toLocaleDateString();
                $("#OrderDate").val(today).trigger('change');
    
            })
            .error(function () {
                alertify.set('notifier', 'position', 'top-right');
                alertify.error('يوجد خطأ', 5);
                return;
            });
        };

    so please how can i empty file uploader after uploaded file ?

    and can you please explain the directive & service because i didn't understand them correctly ?

    Thanks a lot  ...

    Wednesday, June 17, 2015 7:18 AM
  • User2024324573 posted

    You can set 

    $scope.File =null;

    after uploading one file.

    Wednesday, June 17, 2015 7:28 PM
  • User-1846805900 posted

    You can set 

    $scope.File =null;

    after uploading one file.

    Hi

    i try it many time but not working

    i have add it inside success of upload as:

    app.service('fileUpload', ['$http', function ($http, $scope) {
        this.uploadFileToUrl = function (file, uploadUrl) {
            var fd = new FormData();
            fd.append('file', file);
            $http.post(uploadUrl, fd, {
                transformRequest: angular.identity,
                headers: { 'Content-Type': undefined }
            })
            .success(function (data) {
                alertify.set('notifier', 'position', 'top-left');
                alertify.success('تم حفظ الصنف برقم ' + data.id, 5);
    
                $scope.File  = null; // i have add it here but nothing ??!!
            })
            .error(function () {
                alertify.set('notifier', 'position', 'top-right');
                alertify.error('يوجد خطأ', 5);
                return;
            });
        }
    }]);

    and i got error in console:

    Cannot set property 'File' of undefined

    and try to add it inside success  of save data but nothing:

        $scope.saveInvoice = function (data) {
    
            $http.post("/api/customerService/SaveInvoice", $scope.invoice)
    
            .success(function (data) {
                var file = $scope.File;
                var uploadUrl = "/api/customerService/PostFile?id=" + data.ID;
                fileUpload.uploadFileToUrl(file, uploadUrl);
    
                alertify.set('notifier', 'position', 'top-left');
                alertify.success('تم حفظ الفاتورة برقم ' + data.ID, 5);
    
                $scope.File = null; // i add it here but nothing too ??!!
    
                $scope.tax = 0.00;
                $scope.PercentageDiscount = 0.00;
                $scope.MoneyDiscount = 0.00;
                $scope.invoice = { ContactName: "عميل نقدى" };
    
                $scope.orders = [];
                $scope.lastID = data.ID;
    
                var today = new Date().toLocaleDateString();
                $("#OrderDate").val(today).trigger('change');
            })
            .error(function () {
                // called asynchronously if an error occurs
                // or server returns response with an error status.
                alertify.set('notifier', 'position', 'top-right');
                alertify.error('يوجد خطأ', 5);
                return;
            });
        };

    so please what is the problem ?

    Note: data is saved and file is uploaded as i need

    Wednesday, June 17, 2015 8:12 PM
  • User2024324573 posted

    please have a look at this plunker example: http://plnkr.co/edit/xLM9VX?p=preview

    you need to write a function to clear the control.

    Wednesday, June 17, 2015 8:19 PM