Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How To upload file using Angularjs And codeigniter?

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.

like image 509
Abhishek Kadam Avatar asked May 17 '26 23:05

Abhishek Kadam


1 Answers

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.

like image 162
Yogesh Shakya Avatar answered May 20 '26 15:05

Yogesh Shakya



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!