2015-05-27 36 views
0

無法使用AngularJS創建文件上傳。 還有一種形式:如何在AngularJS中上傳文件?

<form ng-submit="getElem()" ng-repeat="elem in elems" class="update-form"> 
    <label for="name">Elem name: {{elem.name}}</label> 
    <input type="file" id="file" name="file" /> 
    <button type="button" ng-click="addImage()" class="btn btn-success"> 
     <span class="glyphicon glyphicon-pencil" aria-hidden="true"></span> 
     Add 
    </button> 
</form> 

而且我在AngularJS的方法:

$scope.addImage = function() { 
     $scope.data = 'none'; 
      var f = document.getElementById('file').files[0], 
       r = new FileReader(), 
       currentElem = this.elem.id; 
      r.onloadend = function(e){ 
       $scope.data = e.target.result; 
       var updateUrl = 'https://example/find' + currentElem + '/images'; 
        $http.post(updateUrl, $scope.data) 
         .success(function (data, status, headers, config) { 
          console.info('Update image fine!'); 
         }); 
      } 
      r.readAsBinaryString(f); 

後,我點擊「添加」按鈕,我有一個錯誤「類型錯誤:未能執行‘readAsBinaryString’在'FileReader'上:參數1不是'Blob'類型。「 爲什麼發生這種情況?而我該如何解決這個問題,因爲我需要上傳文件?

回答

0

以下功能嘗試

$scope.add = function(){ 
    var f = document.getElementById('file').files[0], 
     r = new FileReader(); 
    r.onloadend = function(e){ 
    var data = e.target.result; 
    //send you binary data via $http or $resource or do anything else with it 
    } 
    r.readAsBinaryString(f); 
}