Angularjs上传多个文件

问题描述 投票:0回答:1

我们的团队正在ServiceNow中进行开发,需要能够上传文档并将其附加到案例记录的功能。看了几个例子之后,我们有了一个可行的例子。我们的HTML看起来像这样:

<input type="file" file-model="myFile"/>
<button ng-click="uploadFile()">upload me</button>

在我们的控制器中,我们具有以下内容:

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

我们还创建了一个名为fileUpload的依赖项:

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

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

最后,我们有一个名为fileModel的角度提供程序:

function fileModel($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]);
                }); 
            }); 
        } 
    }; 
}

是否有一种方法可以修改此文件,以便我们可以上传多个文件而不是一个文件?我们在HTML中添加了“多个”,但控制台中仅显示1个文件。我认为我们遗漏了一些显而易见的东西,但似乎无法弄清楚……

angularjs file-upload servicenow
1个回答
0
投票

尝试此代码并检查控制台。

<body ng-app="fileUpload" ng-controller="MyCtrl">
<input type="file" multiple="true" id="fileUpload" file="file"/>
<button ng-click="uploadFile()">upload me</button>
</body>

//inject angular file upload directives and services.
var app = angular.module('fileUpload', ['ngFileUpload']);

app.controller('MyCtrl', ['$scope', 'Upload', '$timeout', function ($scope, Upload, $timeout) {
     $scope.uploadFile = function () {

        var fd = new FormData();
        angular.forEach($scope.file, function (value, key) {
            fd.append(key, value);
        });

         for (var pair of fd.entries()) {
            console.log(pair[0]+ ', ' + pair[1]); 
        }
        console.log("hi")
    };
}]);

app.directive('file', function () {
    return {
        scope: {
            file: '='
        },
        link: function (scope, el, attrs) {
            el.bind('change', function (event) {
                var file = event.target.files;
                scope.file = file ? file : undefined;
                scope.$apply();
            });
        }
    };
})

Codepen-https://jsfiddle.net/PratikPatel227/0rehq8g4/1/(其他)

© www.soinside.com 2019 - 2024. All rights reserved.