2015-06-13 38 views
0

嘿傢伙我想知道如何用另一個用戶上傳的json替換json。如何讓用戶上傳文件並在我的代碼中使用它

這是我的javascript代碼

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

app.controller('mainController', function ($scope, $http) { 
    $http.get('cuidades.json').success(function(data){ 
$scope.cities = data; 
    }); 
}); 

,這是我的HTML代碼,這個代碼,我可以從我的電腦,並以其優良的得到一個JSON,但我不知道如何要求用戶上傳一個文件並加載HIS文件。

<!doctype html> 
<html ng-app="miApp"> 
    <head> 
      <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.10/angular.min.js"> 
    </script> 
     <script src="prueba.js"></script> 
    </head> 

    <body ng-controller="mainController"> 
    <h1>Ciudades</h1> 
    <table> 
     <label>Filtro:</label> 
     <input ng-model="query"> 
     <hr> 
     <tr ng-repeat="city in cities | filter:query | orderBy:'name'"> 
     <td> {{city.name}} - {{city.country}}</td> 
     </tr> 
    </table> 

     <label>Selecciona un archivo para subir</label> 
     <br /> 
     <input type="file" ng-model-instant/> 
    <input type="submit" value='submit'/> 

    </body> 
</html> 
+0

有一個數字,你可以用它來處理這個問題,避免邊緣情況庫。試試這個例子:https://github.com/blueimp/jQuery-File-Upload或者這個角度爲https://github.com/danialfarid/ng-file-upload。如果你的谷歌周圍有一堆其他人,如果這些都不夠。 – Brian

回答

0

正如Brian所說,你可以使用https://github.com/danialfarid/ng-file-upload。 這是我的代碼,基於我發現的搜索範例。

$scope.$watch('foto', function() { 
     $scope.uploadFile($scope.foto); 
    }); 

    $scope.uploadFile = function() { 

     var file; 
     if ($scope.foto) { 
      file = $scope.foto[0]; 
     } 
     if (!file) return; 

     console.log('uploadfile()'); 
     console.log('file', file); 

     $scope.upload = Upload.upload({ 
      url: '/api/photo', 
      method: 'POST', 
      data: angular.toJson($rootScope.usuario), 
      file: file 
     }).progress(function (evt) { 
      $scope.uploadProgress = parseInt(100.0 * evt.loaded/evt.total, 10); 
      console.log('uploadProgress', $scope.uploadProgress); 
     }).success(function (data) { 
      console.log('Sucesso no upload'); 
      console.log('data', data); 
      $rootScope.usuario.foto = '/uploads/' + data.files.file.name; 
     }); 
    }; 

而且我的html代碼:

<input type="file" name="userPhoto" ngf-select ng-model="foto" /> 
<div class="progress" style="margin-top: 20px;"> 
    <div class="progress-bar" progress-bar="uploadProgress" role="progressbar"> 
     <span ng-bind="uploadProgress"></span> 
     <span>%</span> 
    </div> 
</div> 

希望我幫助

相關問題