AngularJS上传本地文件

时间:2015-06-22 14:32:41

标签: angularjs file upload

我尝试上传本地文件,但据我所知,浏览器不支持我使用的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>

1 个答案:

答案 0 :(得分:0)

您可以使用ng upload module ,但有很多方法,但我更喜欢这个模块。 您可以使用像此博客upload file

这样的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); }