0

I'm trying to upload a local file, but I understand that the http.get method I am using is not supported by my browser. Does anyone know of the alternative way I'm supposed to do it?

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

0

You can use ng upload module and there many are ways but I like this module more. You can do it natively using custome directive like this blog upload file

or my way natively

            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 }
            })
            }
            }])

In your mark up

        <form>
        <input type="file" file-model="f.file"></input>

        <button type="submit" class="btn btn-danger" ng-click="submit()">Upload</button>

    </form>

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.