2

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 .

1 Answer 1

2

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;
});
Sign up to request clarification or add additional context in comments.

2 Comments

Can you tell me how it should submit on button click not on file select... @MajoB
@stumps_k2001 you can store your $file in $scope.file = $file and then call service.uploadFile($scope.file on ng-click

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.