1. 程式人生 > >AngularJs 上傳檔案

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