2017-04-07 109 views
0

我使用這樣的事情在角無法獲取fileReader.onload功能

app.controller('techiesClub', function($scope, $http) { 
    $scope.firstName = "John"; 
    $scope.lastName = "Doe"; 

    $scope.asdf = "ankur"; 
    $scope.uploadImage = function() { 
     alert($scope.asdf);   ////////////WORKS WELL 
     var filesSelected = document.getElementById("upload").files; 
     if (filesSelected.length > 0) { 
      var fileToLoad = filesSelected[0]; 

      var fileReader = new FileReader(); 

      fileReader.onload = function(fileLoadedEvent, ss) { 
      var srcData = fileLoadedEvent.target.result; // <--- data: base64 

      $scope.asdf = srcData; //////////////////NOT WORKING 

      } 
      debugger; 
      fileReader.readAsDataURL(fileToLoad, $scope); 
     } 
    } 
}); 

使用uploadImage方法上的onchange一個輸入的這樣

<input type="file" id="upload" name="pic" class="form-control" onchange="angular.element(this).scope().uploadImage()"> 

我無法在$範圍變量獲取srcData,即base64數據到一個變量,我可以使用其他地方。

回答

0

Ankur,

我們可以用這種方法重寫html。

<input type="file" id="upload" name="pic" class="form-control" onchange="angular.element(this).scope().uploadImage(this);"> 

JS代碼片段在這裏..我想與Blob版本。

$scope.uploadImage = function ($event) { 
    alert($scope.asdf);   ////////////WORKS WELL 
    var filesSelected = $event.files; 
    if (filesSelected.length > 0) { 
     var fileToLoad = filesSelected[0]; 
     var _ULR = window.URL || window.webkitURL; 
     var img = new Image(); 
     img.onload = function() { 
     var srcData = this.src; // <--- data: blob 
     $scope.asdf = srcData; //////////////////NOT WORKING 
     };debugger; 
     img.src =_ULR.createObjectURL(fileToLoad); 

    } 
} 
+0

這工作正常,但我不明白如何? –

0

我認爲你錯過了解決方案的關鍵點。我只是改變你訪問base64內容的方式。它應該工作。

$scope.uploadImage = function() { 
    alert($scope.asdf);   ////////////WORKS WELL 
    var filesSelected = document.getElementById("upload").files; 
    if (filesSelected.length > 0) { 
     var fileToLoad = filesSelected[0]; 

     var fileReader = new FileReader(); 

     fileReader.onload = function(fileLoadedEvent) { 
     var srcData = fileReader.result; // <--- data: base64 

     $scope.asdf = srcData; //////////////////NOT WORKING 

     } 
     debugger; 
     fileReader.readAsDataURL(fileToLoad); 
    } 
}