stumps_k2001
stumps_k2001

Reputation: 45

AngularJS Upload File is not Working

I am trying to upload file to read in php. But, I unable to transmit a file over to the php.

My code was,

HTML Code:

<label>Import</label>
 <div class="form-group">
      <input type="file" ng-file-select="uploadFile($files)" />
 </div>

app.js:

var app = angular.module('myApp','ngRoute','myApp.bulk','ngSanitize','angularFileUpload']);

bulk.js

var bulkApp = angular.module('myApp.bulk', ['ngResource','ngRoute','ngSanitize']);


    bulkApp.factory('FileUploadService', function ($http) {
  var api = {
    uploadFile: function (file, callback) {
        alert(file.name);
      $http.uploadFile({
        url: 'xxx/services.php?upload=1',
        file: file
      }).progress(function(event) {
        console.log('percent: ' + parseInt(100.0 * event.loaded / event.total));
      }).error(function (data, status, headers, config) {
        console.error('Error uploading file')
        callback(status);
      }).then(function(data, status, headers, config) {
        callback(null);
      });
    }
  }
  return api;
});

bulkApp.controller('bulkController', function($scope,$rootScope,$filter,FileUploadService) {

   var service = FileUploadService;
    /** 
     *  Handler to upload a new file to the server.
     */
    $scope.uploadFile = function ($files) {
      var $file = $files[0];      
      service.uploadFile($file, function (error) {
        if (error) {
          alert('There was a problem uploading the file.');
        }
        // handle successfully-uploaded file
      })
    }
 });

services.php

if(isset($_REQUEST) && isset($_REQUEST['upload']))
{               
    var_dump($_FILES);
    /* read functionality over here */
}

I referred this link

i am getting TypeError: $http.uploadFile is not a function error.

please help. thanks in advance .

Upvotes: 2

Views: 893

Answers (1)

Marian Ban
Marian Ban

Reputation: 8188

use $upload service instead of $http:

bulkApp.factory('FileUploadService', function ($upload) {
  var api = {
    uploadFile: function (file, callback) {       
      $upload.upload({
        url: 'xxx/services.php?upload=1',
        file: file
      }).progress(function(event) {
        console.log('percent: ' + parseInt(100.0 * event.loaded / event.total));
      }).error(function (data, status, headers, config) {
        console.error('Error uploading file')
        callback(status);
      }).then(function(data, status, headers, config) {
        callback(null);
      });
    }
  }
  return api;
});

Upvotes: 2

Related Questions