AngularJS上传本地文件



我正在尝试上传一个本地文件,但我知道浏览器不支持我使用的http.get方法。有人知道我该怎么做吗?

<!doctype html>
<html ng-app="demoApp">
  <head>
  </head>
  <body ng-controller="demoController">

    Filter City: <input ng-model="filterCity">
    <ul>
    <li ng-repeat="office in offices | filter:filterCity"><u>{{ office.city }}</u> - {{office.name}}</li>
    </ul>

    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.17/angular.min.js"></script>
    <script>
      var demoApp = angular.module("demoApp", []);
      demoApp.controller("demoController", ['$scope', '$http', function($scope, $http) {
        $scope.filterCity = "";
        $scope.offices = [];
        $http.get('/angular-demo/data').success(function(data){
          $scope.offices = data;
        })
      }])
    </script>
  </body>
</html>

你可以使用ng上传模块,有很多方法,但我更喜欢这个模块。你可以使用custome指令像这个博客上传文件一样本地完成

或者我的方式原生

            app.directive('fileModel', ['$parse', function ($parse) {
            return {
            restrrict: 'A',
            link: function (scope, element, attrs) {
                var model = $parse(attrs.fileModel);
                var modelSetter = model.assign;
                element.bind('change', function () {
                    scope.$apply(function () {
                        modelSetter(scope, element[0].files[0]);
                    })
                })
            }
            }
            }])
            app.service('uploader', ['$http', function ($http) {
            this.post = function (uploadUrl, data) {
            var fd = new FormData();
            for (var key in data)
                fd.append(key, data[key]);
            $http.post(uploadUrl.fd, {
                transformRequest: angular.identity,
                headers: { 'Content-Type': undefined }
            })
            }
            }])

在您的标记中

        <form>
        <input type="file" file-model="f.file"></input>
        <button type="submit" class="btn btn-danger" ng-click="submit()">Upload</button>
    </form>

您的控制器$scope.f = {}; $scope.f.Id = 2; $scope.f.tr = 'hi'; $scope.submit = function () { var uploadUrl = 'https://angular-file-upload-cors-srv.appspot.com/upload'; uploader.post(uploadUrl, $scope.f.file); }

相关内容

  • 没有找到相关文章

最新更新