AngularJs 上传文件

HTML:


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

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

以上方式不可自动把文件同file-model关联, 也就是myFile始终是未定义的。

可以通过一下方式改善:

      <input ng-file-select="onFileSelect($files)" type="file" accept=".csv" > 

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

controller.js:    

$scope.onFileSelect = function (files) {
     $scope.myFile = files;
     console.info('files', files);
    };
   $scope.uploadFile = function(){
        var file = $scope.myFile;
        console.log('file is ' );
        console.dir(file);
        var uploadUrl = "/fileUpload";
        fileUpload.uploadFileToUrl(file, uploadUrl);
    };

ngfileselect.directive.js

  'use strict';
angular.module('idm-admin-ui')
.directive('ngFileSelect', [ '$parse', '$timeout', function($parse, $timeout) {
    return function(scope, elem, attr) {
            var fn = $parse(attr['ngFileSelect']);
            elem.bind('change', function(evt) {
                var files = [], fileList, i;
                fileList = evt.target.files;
                if (fileList != null) {
                    for (i = 0; i < fileList.length; i++) {
                        files.push(fileList.item(i));
                    }
                }
                $timeout(function() {
                    fn(scope, {
                        $files : files,
                        $event : evt
                    });
                });
            });
        };
    }])

fileupload.service.js

  'use strict';
angular.module('idm-admin-ui')
.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(){
             console.log("success------------------");
        })
        .error(function(){
             console.log("error------------------");
        });
    }
}]);
阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/tina_tian1/article/details/52368443
个人分类: AngularJS
上一篇NodeJS基本
下一篇Javascript this
博主设置当前文章不允许评论。

没有更多推荐了,返回首页

关闭
关闭