AngularJS上传文件无效

时间:2014-11-11 07:19:57

标签: php jquery html5 angularjs file-upload

我正在尝试上传文件以在php中读取。但是,我无法将文件传输到php。

我的代码是,

HTML代码:

<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 */
}

我提到了link

我收到TypeError:$ http.uploadFile不是函数错误。

请帮忙。提前谢谢。

1 个答案:

答案 0 :(得分:2)

使用$ upload服务而不是$ 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;
});