3

Here is my angularjs code: In Controller:

var formdata = new FormData();
    $scope.getTheFiles = function ($files) {
        console.log($files);
        angular.forEach($files, function (value, key) {
            formdata.append(key, value);
        });
    };
    // NOW UPLOAD THE FILES.
    $scope.uploadFiles = function () {

        var request = {
            method: 'POST',
            url: 'server/appointments/uploadedFiles',
            data: formdata,

            headers: {
                'X-API-KEY': $rootScope.currentUser.key,
                'Content-Type': undefined
            }
        };

        // SEND THE FILES.
        $http(request)
            .success(function (d) {
                console.log(d);
            })
            .error(function (e) {
                console.log(e);
            });
    }
}

And In Directive:

.directive('ngFiles', ['$parse', function ($parse) {

        function fn_link(scope, element, attrs) {
            var onChange = $parse(attrs.ngFiles);
            element.on('change', function (event) {
                onChange(scope, { $files: event.target.files });
            });
        };

        return {
            link: fn_link
        }
    } ]);

For API i use codeigniter:

function uploadedFiles_POST()
{
    function do_upload()
    {
        if ($this->input->post('Upload')) {
            $config['upload_path'] = './Appointments/';
            $config['allowed_types'] = 'gif|jpg|png';
            $config['max_size'] = '1024';
            $config['max_width'] = '1024';
            $config['max_height'] = '768';
            $this->load->library('upload', $config);
            if (!$this->upload->do_upload()) {
                $error = array('error' => $this->upload->display_errors());

            } else {
                $data = $this->upload->data();

                $file = array(
                    'img_name' => $data['raw_name'],
                    'ext' => $data['file_ext'],
                    'upload_date' => time()
                );
                $this->appointments_model->add_image($file);
                $data = array('upload_data' => $this->upload->data());

            }
        } else {
            redirect(site_url('upload'));
        }
    }
}

And in codeigniter model:

function add_image($data)
    {
        $this->db->where('id', '395');
        return $this->db->update('user_appoint', $data);
    }

My problem is browser detect file name in developer tool but file cant upload to database. it show 500 status.

1 Answer 1

1

For this use angular file upload down load it from here :

https://github.com/nervgh/angular-file-upload

Use this controller:

app.controller('FileUploadCtrl', ['$scope', 'FileUploader', function($scope, FileUploader) 
{
    var uploader = $scope.uploader = new FileUploader({
        url: 'Your Api path',
        autoUpload: true,
    });

    // FILTERS

    uploader.filters.push({
        name: 'customFilter',
        fn: function(item /*{File|FileLikeObject}*/, options) {
            return this.queue.length < 10;
        }
    });

    // CALLBACKS

    uploader.onWhenAddingFileFailed = function(item /*{File|FileLikeObject}*/, filter, options) {
        console.info('onWhenAddingFileFailed', item, filter, options);
    };
    uploader.onAfterAddingFile = function(fileItem) {
        console.info('onAfterAddingFile', fileItem);
    };
    uploader.onAfterAddingAll = function(addedFileItems) {
        console.info('onAfterAddingAll', addedFileItems);
    };
    uploader.onBeforeUploadItem = function(item) {
        console.info('onBeforeUploadItem', item);
    };
    uploader.onProgressItem = function(fileItem, progress) {
        console.info('onProgressItem', fileItem, progress);
    };
    uploader.onProgressAll = function(progress) {
        console.info('onProgressAll', progress);
    };
    uploader.onSuccessItem = function(fileItem, response, status, headers) {
        console.info('onSuccessItem', fileItem, response, status, headers);
        $('.alert').addClass('hide');
        if(response.error) {
          $('.alert-danger').html(response.message).removeClass('hide');
        } else {
          $scope.user.newimg = response.newfilename;
        }
    };
    uploader.onErrorItem = function(fileItem, response, status, headers) {
        console.info('onErrorItem', fileItem, response, status, headers);
    };
    uploader.onCancelItem = function(fileItem, response, status, headers) {
        console.info('onCancelItem', fileItem, response, status, headers);
    };
    uploader.onCompleteItem = function(fileItem, response, status, headers) {
        console.info('onCompleteItem', fileItem, response, status, headers);
    };
    uploader.onCompleteAll = function() {
        console.info('onCompleteAll');
    };

    console.info('uploader', uploader);
}]);

View should be like this:

<div ng-controller="FileUploadCtrl">
<div class="form-group">
<label class="control-label">Image</label>
<input type="file" nv-file-select="" uploader="uploader" /> 
</div>                     
</div>

And your Api method should be like this:

public function user_image_upload()
{

    $json = array();

    $config['upload_path']          = 'assets/avatar/';
    $config['allowed_types']        = 'gif|jpg|png';
    $config['encrypt_name']                 = TRUE;

    $this->load->library('upload', $config);

    $this->upload->initialize($config);

    if ( ! $this->upload->do_upload('file') )
    {
        $json = array('error' => true, 'message' => $this->upload->display_errors());
    }
    else
    {
        $upload_details = $this->upload->data();

        $json = array('success' => true, 'message' => 'File transfer completed', 'newfilename' => $upload_details['file_name']);
    }

    $this->json($json);
}

hopefully it will help you.

Sign up to request clarification or add additional context in comments.

20 Comments

How to use those angular file and where to put.
add it on your angular route script...r u using angular route??
Yes i am using angular route, but still i have not idea where to put those file in my project and how it will accessible.
Suppose your route is this: .state('app.user.list', { url: '/list', templateUrl: 'user.tpl', }) than use this as: .state('app.user.list', { url: '/list', templateUrl: 'user.tpl', resolve: load( ['filepath/angular-file-upload.js'] ) })
If you are still facing problem than include it in header
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.