angularjs文件上傳

參考: http://jsfiddle.net/JeJenny/ZG9re/app

<div ng-controller = "myCtrl">ide

    <input type="file" file-model="myFile"/>post

    <button ng-click="uploadFile()">upload me</button>this

</div>.net


var myApp = angular.module('myApp', []);rest


myApp.directive('fileModel', ['$parse', function ($parse) {orm

    return {element

        restrict: 'A',get

        link: function(scope, element, attrs) {input

            var model = $parse(attrs.fileModel);

            var modelSetter = model.assign;

            

            element.bind('change', function(){

                scope.$apply(function(){

                    modelSetter(scope, element[0].files[0]);

                });

            });

        }

    };

}]);


myApp.service('fileUpload', ['$http', function ($http) {

    this.uploadFileToUrl = function(file, uploadUrl){

        var fd = new FormData();

        fd.append('file', file);

        $http.post(uploadUrl, fd, {

            transformRequest: angular.identity,

            headers: {'Content-Type': undefined}

        })

        .success(function(){

        })

        .error(function(){

        });

    }

}]);


myApp.controller('myCtrl', ['$scope', 'fileUpload', function($scope, fileUpload){

    

    $scope.uploadFile = function(){

        var file = $scope.myFile;

        console.log('file is ' );

        console.dir(file);

        var uploadUrl = "/fileUpload";

        fileUpload.uploadFileToUrl(file, uploadUrl);

    };

    

}]);

相關文章
相關標籤/搜索