Form Post and File Uplaod with AngularJS

I was developing a module using PHP and AngularJS and had to post a form with few fields and a file upload. I did not get any post which to describe the process of adding fileds and logo with AngularJS. I found many blogs for single and multiple file upload methods but not with fields. Here are the steps to develop the form with file upload in AngularJS. In the below example, I am adding an organization with name, address and organization logo.

Step 1.

Add a form Submit controller as “my_controller.js”

(function() {
    'use strict';
    /* Controllers */ 
    var myControllers = angular.module('myApp', ['ngFileUpload']);

    myControllers.controller('MyCtrl', ['$scope', '$http', 'Upload',
        function ($scope, $http, Upload) {  
            // Success or Error Messages
            $scope.message = {type: 'success', text: '', display: false};  
             
            $scope.uploaded_logo = false;
            $scope.uploaded_logo_thumb = false;  

           

            // Hide message container
            $scope.hideMsg = function(){
                $scope.message = {type: 'success', text: '', display: false};  
            };   

            // Add organization submit handler
            $scope.submitAddOrganization = function() { 
                //console.log('called submit');

                var files = $scope.logo;

                if (files && files.length) { 
                    var file = files[0];
                    Upload.upload({
                        url: 'upload_organization_logo', 
                        file: file
                    }).progress(function (evt) {
                        //console.log(evt);
                        // Math.min is to fix IE which reports 200% sometimes
                        file.progress = Math.min(100, parseInt(100.0 * evt.loaded / evt.total));
                        //console.log('progress: ' + file.progress + '% ' + evt.config.file.name);
                    }).success(function (data, status, headers, config) {  
                        if(data.upload_flag)
                        { 
                            $scope.uploaded_logo = data.logo; 
                            $scope.uploaded_logo_thumb = data.logo_thumb;  
                            addOrganization(); 
                        } 
                        $scope.message = {type: data.message_type, text: data.upload_msg, display: true}; 
                        //console.log('file ' + config.file.name + ' uploaded. Response: ' + data);
                    }).error(function (data, status, headers, config) {
                        alert('file upload failed');
                        console.log('error status: ' + status);
                    })
                }
                else
                {
                   addOrganization(); 
                }  
            };  

            // Add organization
            var addOrganization = function() { 
                //console.log('called addOrganization'); 
                var params = { 
                    'name': $scope.name, 
                    'address': $scope.address, 
                    'city': $scope.city, 
                    'zip': $scope.zip,  
                    'logo': $scope.uploaded_logo,
                    'logo_thumb': $scope.uploaded_logo_thumb,
                    'description': $scope.description
                }; 
                 
                //console.log(params);
                $http.post('add_organization', JSON.stringify(params)).
                    success(function(data, status, headers, config, statusText) { 
                        //console.log(data); console.log(data.id); console.log(data.message);
                        if(data.id)
                        {
                            $scope.message = {type: 'success', text: data.message, display: true}; 
                            reset_form_fields(scope);
                        }
                        else
                        {
                            $scope.message = {type: 'error', text: data.message, display: true}; 
                        } 
                    }).
                    error(function(data, status, headers, config, statusText) { 
                        var msg = "failure message: " + JSON.stringify({data: data});
                        $scope.message = {type: 'error', text: msg, display: true}; 
                    }
                );  
            };  
        }
    ]);  

    

    function reset_form_fields(scope) { 
        scope.name = '';
        scope.address = '';
        scope.city = '';
        scope.zip = ''; 
        scope.logo = '';
        scope.logo_thumb = ''; 
        scope.description = '';  
    }

})();

I am assuming you have included angular.js and ngfileupload.js with required files.
In the above controller, first we have to add dependency on ngFileUpload Module. Set the mode to add or update and update_id will be false in case of adding new organization.

Submit add organization checks if logo is selected, upload it then call add_organization function else call add_organization without file upload.

Add a HTML file as “my_form.html”

 
<div class="row" ng-app="myApp" ng-controller="MyCtrl" ng-cloak>
    <div class="col-xs-12">
        <!-- PAGE CONTENT BEGINS -->   
		<div class="row">  
            <div class="col-xs-12">   
                <div class="alert" ng-class="{error:'alert-danger', success:'alert-block alert-success'}[message.type]" ng-show="message.display">
                    <button type="button" class="close" ng-click="hideMsg()">
                        <i class="ace-icon fa fa-times"></i>
                    </button> 
                    <i class="ace-icon fa fa-check" ng-class="{success:'green'}[message.type]"></i>
                    {{message.text}}      
                </div> 

                <!-- Add Organization Start-->
                <div class="widget-box">
                    <div class="widget-header widget-header-flat widget-header-small">
                        <h5 class="widget-title">
                            <i class="ace-icon fa fa-plus"></i>
                            Add Organization
                        </h5> 
                    </div>

                    <div class="widget-body">
                        <div class="widget-main">
                            <!-- PAGE CONTENT BEGINS -->  
                            <form name="frmAddOrg" class="form-horizontal" ng-submit="frmAddOrg.$valid && submitAddOrganization()" novalidate>  
                            <div class="form-group">
                                <label class="col-sm-3 control-label no-padding-right" for="form-field-name">Name <i class="red ace-icon fa fa-asterisk smaller-60 align-top"></i></label> 
                                <div class="col-sm-9">
                                    <div class="clearfix">
                                        <input type="text" class="col-sm-12" name="name" id="name" ng-model="name" placeholder="Name" ng-minlength="5" ng-maxlength="255" required />
                                    </div> 

                                    <div class="has-error" ng-show="frmAddOrg.name.$dirty && frmAddOrg.name.$invalid">
                                        <small class="help-block" ng-show="frmAddOrg.name.$error.required">
                                            Organization name is required.
                                        </small>
                                        <small class="help-block" ng-show="frmAddOrg.name.$error.minlength">
                                            Organization name is required to be at least 5 characters
                                        </small>
                                        <small class="help-block" ng-show="frmAddOrg.name.$error.maxlength">
                                            Organization name cannot be longer than 255 characters
                                        </small>
                                    </div> 
                                </div>
                            </div>      

                            <div class="form-group">
                                <label class="col-sm-3 control-label no-padding-right" for="form-field-address">Address</label> 
                                <div class="col-sm-9">
                                    <input type="text" class="col-sm-12" maxlength="255" name="address" id="address" ng-model="address" placeholder="Address" />
                                </div>
                            </div>    

                            <div class="form-group">
                                <label class="col-sm-3 control-label no-padding-right" for="form-field-city">City</label> 
                                <div class="col-sm-9">
                                    <input type="text" class="col-sm-12" maxlength="255" name="city" id="city" ng-model="city" placeholder="City" />
                                </div>
                            </div>    

                            <div class="form-group">
                                <label class="col-sm-3 control-label no-padding-right" for="form-field-zip">Zip</label> 
                                <div class="col-sm-9">
                                    <input type="text" class="col-sm-12" maxlength="255" name="zip" id="zip" ng-model="zip" placeholder="Zip" />
                                </div>
                            </div>   

                            <div class="form-group">
                                <label class="col-sm-3 control-label no-padding-right" for="form-field-logo"> 
                                    Logo
                                </label>
                                <div class="col-sm-9"> 
                                    <!--  ngf-min-size="10" ngf-max-size="100" --> 
                                    <button ngf-select ng-model="logo" accept="image/*" class="btn btn-minier btn-round btn-success">Upload Logo</button>  
                                    <img ngf-src="logo[0]" ngf-default-src="{{site_url}}uploads/organizations/no-logo.png" ngf-accept="'image/*'" class="organization-logo"> 
                
                                    <div class="help-block" ng-show="logo[0].progress >= 0">
                                        <div class="progress progress-striped active">
                                            <div ng-bind="logo[0].progress + '%'" style="width: {{logo[0].progress}}%;" class="progress-bar progress-bar-warning"></div>
                                        </div> 
                                    </div> 
                                </div>
                            </div> 

                            <div class="form-group">
                                <label class="col-sm-3 control-label no-padding-right" for="form-field-description">Description</label> 
                                <div class="col-sm-9">
                                    <div class="clearfix"> 
                                        <textarea name="description" id="description" ng-model="description" class="col-sm-12" ng-minlength="5" ng-maxlength="1255"></textarea>
                                    </div> 

                                    <div class="has-error" ng-show="frmAddOrg.description.$dirty && frmAddOrg.description.$invalid"> 
                                        <small class="help-block" ng-show="frmAddOrg.description.$error.minlength">
                                            Organization Description is required to be at least 5 characters
                                        </small>
                                        <small class="help-block" ng-show="frmAddOrg.description.$error.maxlength">
                                            Organization Description cannot be longer than 1255 characters
                                        </small>
                                    </div> 
                                </div>
                            </div> 



                            <div class="clearfix">
                                <div class="col-md-offset-3 col-md-9">
                                    <button class="btn btn-info btn-minier btn-round" type="submit" ng-disabled="frmAddOrg.$invalid">
                                        <i class="ace-icon fa fa-check"></i>
                                        Submit
                                    </button>
                                    <button type="reset" class="btn btn-minier btn-round">
                                        <i class="ace-icon fa fa-undo"></i>
                                        Reset
                                    </button> 
                                    <button ng-click="hide_add_organization_container()" type="button" class="btn btn-info btn-minier btn-round">
                                        <i class="ace-icon fa fa-reply"></i>
                                        Cancel
                                    </button> 


                                </div>
                            </div>  
                            </form>  
                            <!-- PAGE CONTENT ENDS -->
                        </div><!-- /.widget-main -->
                    </div><!-- /.widget-body -->
                </div> 
                <!-- Add Organization End--> 
            </div> 
		</div> 
        <!-- PAGE CONTENT ENDS -->
    </div><!-- /.col -->
</div><!-- /.row --> 

Leave a Reply

Your email address will not be published. Required fields are marked *