如何要求用户上传文件并在我的代码中使用它

How to ask the user to upload a file and use it in my code

大家好,我想知道如何用用户上传的另一个 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 并且它很好,但我不知道如何要求用户上传文件和加载他的文件。

<!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>

正如 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>

希望我能帮到你