如何在Angularjs中单击一次即可实现多个文件上传

时间:2017-02-18 11:02:59

标签: javascript angularjs file-upload multiple-file-upload

我有以下代码片段,单个文件上传很好。 我的目标是将用户从ngrepeat上传的文件发送到我的控制器。

目前我想知道多个文件上传如何在单击中工作。

以下代码适用于单个文件但不适用于多个文件。 请帮助我在哪里犯错误?

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);
        $scope.d.file = file;
        console.log($scope.d)
        var uploadUrl = "/fileUpload";
        fileUpload.uploadFileToUrl(file, uploadUrl);
    };
    
}]);
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body ng-app="myApp">
<div ng-controller = "myCtrl">
    <input type="file" file-model="myFile"/>

    <input type="text" ng-model="d.name">
    <button ng-click="uploadFile()">upload me</button>
</div>
</body>
</html>

1 个答案:

答案 0 :(得分:1)

愿这个链接可以帮到你

Multiple File Upload in Angularjs