HTML5/JS - 在div中显示多个文件输入

The*_*ver 8 javascript jquery html5

我正在使用HTML5精彩的"多重"文件选择功能.

<input type="file" id="fileInput" onChange="runTest()" multiple>
Run Code Online (Sandbox Code Playgroud)

我想在输入字段下面显示所选的文件名,并使用CSS看起来很漂亮,但是......

如果我运行一个测试JS函数,它"警告"我输入字段的值,它只显示一个文件而不管我选择10.

function runTest() {
var fileInput = document.getElementById('fileInput').value;
alert("You selected: "+fileInput);
}
Run Code Online (Sandbox Code Playgroud)

当我有一个'单个'文件输入字段并且工作正常但是现在它是'多个'时,我正在这样做,它不喜欢它.

有什么建议?

Dav*_*mas 7

好吧,似乎val()元素返回的值是仅选择的最后一个文件的名称.要解决这个问题,使用多变量事件的性质可能是明智的:

$('input:file[multiple]').change(
    function(){
        $('ul').append($('<li />').text($(this).val()));
    });
Run Code Online (Sandbox Code Playgroud)

JS小提琴演示.

并将名称输出到列表(如示例中所示),或将最新值附加到数组,或者,可能使用/创建隐藏输入来存储文件名,因为您觉得最适合您的应用程序.

要访问文件名(以及上次修改日期,文件大小...),您可以(在Chromium 12/Ubuntu 11.04中测试)使用以下内容:

$('input:file[multiple]').change(
    function(e){
        console.log(e.currentTarget.files);
    });
Run Code Online (Sandbox Code Playgroud)

JS小提琴演示.


编辑使上述内容稍微有用,并且有希望展示:

$('input:file[multiple]').change(
    function(e){
        console.log(e.currentTarget.files);
        var numFiles = e.currentTarget.files.length;
            for (i=0;i<numFiles;i++){
                fileSize = parseInt(e.currentTarget.files[i].fileSize, 10)/1024;
                filesize = Math.round(fileSize);
                $('<li />').text(e.currentTarget.files[i].fileName).appendTo($('#output'));
                $('<span />').addClass('filesize').text('(' + filesize + 'kb)').appendTo($('#output li:last'));
            }
    });
Run Code Online (Sandbox Code Playgroud)

JS小提琴演示.

由于Webkit,Chrome 24(尽管可能来自早些时候)的变化,最后的代码块更新,由nextgentech在评论中,如下:

$('input:file[multiple]').change(
    function(e){
        console.log(e.currentTarget.files);
        var numFiles = e.currentTarget.files.length;
            for (i=0;i<numFiles;i++){
                fileSize = parseInt(e.currentTarget.files[i].size, 10)/1024;
                filesize = Math.round(fileSize);
                $('<li />').text(e.currentTarget.files[i].name).appendTo($('#output'));
                $('<span />').addClass('filesize').text('(' + filesize + 'kb)').appendTo($('#output li:last'));
            }
    });
Run Code Online (Sandbox Code Playgroud)

JS小提琴演示.