码迷,mamicode.com
首页 > Web开发 > 详细

angularjs文件上传

时间:2015-09-08 18:39:26      阅读:155      评论:0      收藏:0      [点我收藏+]

标签:

参考: http://jsfiddle.net/JeJenny/ZG9re/

<div ng-controller = "myCtrl">

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

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

</div>


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


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

    return {

        restrict: ‘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]);

                });

            });

        }

    };

}]);


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

    };

    

}]);


angularjs文件上传

标签:

原文地址:http://my.oschina.net/u/1453451/blog/502885

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!