2016-04-19 15 views
1

Angularjs経由でファイルをアップロードしようとしています。私はサービスを打っていますが、サーバー上のファイルを取得できません。私は以下のコードを投稿しました。コードのエラー/修正を教えてください。サービスにファイルを正常に投稿できません。

<html> 

<head> 
    <script src = "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script> 
</head> 

<body ng-app = "myApp"> 

    <div ng-controller = "myCtrl"> 
    <form name="demo"> 
     <input type = "file" file-model = "myFile"/> 
     <button type="submit" ng-click = "uploadFile()">upload me</button> 
    </form> 
    </div> 

    <script> 
    var myApp = angular.module('myApp', []); 

    myApp.directive('fileModel', ['$parse', function ($parse) { 
     return { 
      restrict: 'A', 
      link: function(scope, element, attrs) { 
       var model = $parse(attrs.fileModel); 
       var modelSetter = model.assign; 

       element.bind('change', function(){ 
       scope.$apply(function(){ 
        modelSetter(scope, element[0].files[0]); 
       }); 
       }); 
      } 
     }; 
    }]); 

    myApp.service('fileUpload', ['$http', function ($http) { 
     this.uploadFileToUrl = function(file, uploadUrl){ 
      var fd = new FormData(); 
      fd.append('file', file); 

      $http.post(uploadUrl, fd, { 
       transformRequest: angular.identity, 
       headers: {'Content-Type': undefined} 
      }) 

      .success(function(){ 
       console.log('file uploaded'); 
      }) 

      .error(function(){ 
       console.log('file not uploaded'); 
      }); 
     } 
    }]); 

    myApp.controller('myCtrl', ['$scope', 'fileUpload', function($scope, fileUpload){ 
     $scope.uploadFile = function(){ 
      var file = $scope.myFile; 

      console.log('file is '); 
      console.dir(file); 

      var uploadUrl = "http://172.29.5.86:8080/marketplace/inventory/testImageUpload.service"; 
      fileUpload.uploadFileToUrl(file, uploadUrl); 
     }; 
    }]); 

    </script> 

答えて

1

私はhttps://github.com/flowjs/ng-flowを使用することをお勧めいたしますすることができます。

HTML

<div flow-init 
    flow-name="flowObject.flow"   <!-- optional --> 
    flow-file-added="fileAdded($file)"> <!-- optional --> 

    <!-- Your HTML --> 
    <span class="btn btn-default" data-flow-btn>Select Files</span> 
    <span class="btn btn-primary" ng-click="uploadFiles()">Upload</span> 
</div> 

コントローラ

$scope.flowObject = {}; 

$scope.uploadFiles = function() { 
    $scope.files = $scope.flowObject.flow.files; 

    // some logic 

    myService.uploadFilesSomewhere($scope.files).then(function (response) { 
     // some other logic 
    }); 
}; 

$scope.fileAdded = function (file) { 
    // some logic 
}; 
+0

私はいくつかのプラグインや他人のコードよりも自分自身をそれを行うにしたいと思います。現在のコードのボトルネックを教えてください。 – kushalvm

関連する問題