简体   繁体   English

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

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

Hey guys I'm trying to know how to replace a json with another json a user upload. 大家好,我想知道如何用用户上传的另一个json替换json。

This is my javascript code 这是我的JavaScript代码

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

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

And this is my html code, with this code I can get a json from my computer and its fine but I don't know how to ask the user to upload a file and load HIS file. 这是我的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>

As Brian said you can use https://github.com/danialfarid/ng-file-upload . 正如Brian所说,您可以使用https://github.com/danialfarid/ng-file-upload This is my code, based on a sample I found googling around. 这是我的代码,基于我发现的谷歌搜索示例。

    $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;
        });
    };

And my html code: 而我的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>

Hope I helped 希望我能帮上忙

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM