读取多个文件输入

时间:2015-08-31 06:49:59

标签: javascript angularjs

这是我读取文件输入中第一项的代码,如何迭代此输入中的所有项目?

function readFile (uploadControlId) {
    if (!window.FileReader)
        throw "The browser does not support HTML 5";

    var element = document.getElementById(uploadControlId);

    var def = new $.Deferred();

    var file = element.files[0];
    var parts = element.value.split("\\");
    var fileName = parts[parts.length - 1];

    var reader = new FileReader();
    reader.onload = function (e) {
        if (uploadControlId == 'uploadControlId'){
            def.resolve(e.target.result, fileName);
        } else {
            def.resolve(e.target.result, fileName);
        }

    };
    reader.onerror = function (e) {
        def.reject(e.target.error);
    };

    reader.readAsArrayBuffer(file);
    return def.promise();
}

我尝试过类似的事情:

angular.forEach(element.files, function (file){
})

但这不起作用,因为变量'parts'和'fileName'来自变量'element',所以如果我遍历元素中的每个文件,它们会得到'undefined'fileName,这意味着它们不会有像.txt或.pdf,所以它们是不可读的。

更新:这不会出错,但只会上传最后一个文件:

    function readFile (uploadControlId) {
    if (!window.FileReader)
        throw "The browser does not support HTML 5";

    var def = new $.Deferred();

    var element = document.getElementById(uploadControlId);

    angular.forEach(element.files, function(file){

        var fileName = file.name;

        var reader = new FileReader();
        reader.onload = function (e) {
            def.resolve(e.target.result, fileName);
        };
        reader.onerror = function (e) {
            def.reject(e.target.error);
        };

        reader.readAsArrayBuffer(file);
    });
    return def.promise();
}

我的上传功能:

$scope.UploadAttachment = function(){
    readFile(uploadControlId).done(function (buffer, fileName) {

// logic to upload to server

    }).fail(function (err) {
        alert("error in reading file content");
    });

};

1 个答案:

答案 0 :(得分:2)

您是否添加了"多个"输入标签上的属性?

顺便说一下,如果你将这个指令添加到你的标签中,将会触发一个包含所有文件的事件,你将在你的控制器中处理它。

// Directive
(function(){

    var Directive = function(){
        return {
            restrict: 'A',
            scope : {},
            link : function(scope, element, attrs){
                element.bind('change', function(changeEvent){
                    scope.$emit('fileReader', changeEvent.target.files);
                });
            }
        }
    };

    Directive.$inject = [];

    app.directive('fileReader', Directive);

})();

// Controller
(function(){

    var Controller = function($scope){

        // Methods
        function fileReader(files){

            for(var iFile = 0, fileLen = files.length; iFile < fileLen; iFile = iFile + 1){
                var file = files[iFile];
                // Do something
            }

        }

        // Events
        $scope.$on('fileReader', function(event, files){
            fileReader(files);
        });


    };

    Controller.$inject = [
        '$scope'
    ];

    app.controller('MainCtrl', Controller);

})();