angularjs使用单个上传按钮上传文件

时间:2017-06-19 03:25:00

标签: angularjs file-upload

我想知道如何在不使用外部库而只使用单个上传按钮的情况下使用angularjs上传文件? 我已经搜索了一段时间的解决方案,发现解决方案非常接近我想要的,如下所示:

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

}]);

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

但是,我只想要一个上传按钮,在上面的例子中,我该如何触发uploadFile()?

1 个答案:

答案 0 :(得分:1)

更新了您的小提琴:http://jsfiddle.net/ZG9re/7080/

<强> HTML

<div ng-controller = "myCtrl">    
    <button>
    <input type="file" class="input" id="myfile" file-model="myFile"><a href="">Upload Me</a>
    </button>    
</div>

<强> CSS

#myfile {
  opacity: 0;
  position: absolute;
}

现在当你点击&#34;上传我&#34;你将获得文件浏览器。

<强>更新

请检查:http://jsfiddle.net/ZG9re/7081/