Angularjs文件上传不起作用($ files未定义)

时间:2014-09-03 10:19:02

标签: javascript angularjs file-upload angular-file-upload

我使用danialfarid库fileUpload。

https://github.com/danialfarid/angular-file-upload 我在GitHub页面上的#34;用法文章和#34;中做了同样的事情,但是在我选择文件之后我有一个错误:" Uncaught TypeError:无法读取属性' length'未定义"这个未定义的是$ files。

这是我的控制器:

$scope.onFileSelect = function($files) {
  console.log($files); // undefined
//$files: an array of files selected, each file has name, size, and type.
for (var i = 0; i < $files.length; i++) {
  var file = $files[i];
  $scope.upload = $upload.upload({
    url: '/cards/avatar/save_from_disk', //upload.php script, node.js route, or servlet url
    data: {myObj: $scope.myModelObj},
    file: file,
  }).progress(function(evt) {
    console.log('percent: ' + parseInt(100.0 * evt.loaded / evt.total));
  }).success(function(data, status, headers, config) {
    // file is uploaded successfully
    console.log(data);
  });
}

};

在我看来:

<input type="file" title="" accept="image/*"  ng-file-select="onFileSelect($files)" class="upload" />

1 个答案:

答案 0 :(得分:2)

更有可能你错过了一些东西,请参阅应该有帮助的工作示例: http://plnkr.co/edit/fbALEktGuyDY2CNUrwrL?p=preview

<强> JS:

var app = angular.module('plunker', ['angularFileUpload']);

app.controller('MainCtrl',['$scope', '$upload', function($scope, $upload) {


    $scope.onFileSelect = function($files) {


      console.log($files); // undefined
      //$files: an array of files selected, each file has name, size, and type.
      for (var i = 0; i < $files.length; i++) {
        var file = $files[i];
        $scope.upload = $upload.upload({
          url: '/cards/avatar/save_from_disk', //upload.php script, node.js route, or servlet url
          data: {
            myObj: $scope.myModelObj
          },
          file: file,
        }).progress(function(evt) {
          console.log('percent: ' + parseInt(100.0 * evt.loaded / evt.total));
        }).success(function(data, status, headers, config) {
          // file is uploaded successfully
          console.log(data);
        });
      }
    };
  }
]);

<强> HTML:

<!DOCTYPE html>
<html ng-app="plunker">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>

    <link rel="stylesheet" href="style.css" />
    <script data-require="angular.js@1.2.x" src="https://code.angularjs.org/1.2.22/angular.js" data-semver="1.2.22"></script>
      <script src="http://angular-file-upload.appspot.com/js/angular-file-upload.js"></script>
    <script src="app.js"></script>
  </head>

  <body ng-controller="MainCtrl">

    <input type="file" title="" accept="image/*"  ng-file-select="onFileSelect($files)" class="upload" />
  </body>

</html>