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

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

本文关键字:代码 我的 文件 用户      更新时间:2023-09-26

嘿伙计们,我想知道如何将一个 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>

正如布莱恩所说,你可以使用 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>

希望我有帮助