问题描述
我正在使用HTML5精彩的多重文件选择功能。
I am using HTML5's wonderful 'multiple' file select feature.
<input type="file" id="fileInput" onChange="runTest()" multiple>
我想在输入字段下方显示所选的文件名,并使其看起来很漂亮,但是...
I would like to display the selected filenames below the input field and make it look pretty with CSS, however...
如果我运行一个测试JS函数,它警告我输入字段的值,它只显示一个文件而不管我选择10。
If I run a test JS function, that 'alerts' me of the input field's value, it only shows one file regardless of me selecting 10.
function runTest() {
var fileInput = document.getElementById('fileInput').value;
alert("You selected: "+fileInput);
}
当我有一个'单个'文件输入字段时我正在这样做工作还可以,但现在它是'倍数',它不喜欢它。
I was doing this for when I had a 'single' file input field and worked okay but now it's 'multiple', it doesn't like it.
有什么建议吗?
推荐答案
好吧,元素返回的值或 val()
似乎只是所选最后一个文件的名称。要解决这个问题,最好使用多变量事件的性质:
Well, it seems the value, or val()
, returned by the element is the name of only the last file selected. To work around this, it might be wise to use the nature of the multiple-change events:
$('input:file[multiple]').change(
function(){
$('ul').append($('<li />').text($(this).val()));
});
。
并将名称输出到列表(如示例中所示),或将最新值附加到数组,或者,可能使用/创建隐藏的输入来存储文件名,因为您觉得最适合您的应用程序。
And either output the names to a list (as in the example), or append the latest value to an array, or, possibly, use/create hidden inputs to store the filenames as you feel would best suit your application.
访问文件名(以及上次修改)日期,文件大小......)你可以(在Chromium 12 / Ubuntu 11.04中测试)使用以下内容:
To access the file-names (as well as last modified date, file-size...) you can (tested in Chromium 12/Ubuntu 11.04) use the following:
$('input:file[multiple]').change(
function(e){
console.log(e.currentTarget.files);
});
。
已编辑到使上述内容稍微有用,并且希望是示范性的:
Edited to make the above slightly more useful and, hopefully, demonstrative:
$('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'));
}
});
。
由于Webkit,Chrome 24的变化(尽管可能来自之前的版本),最终的代码块已更新,在的评论中,如下:
The final code-block updated, due to changes in Webkit, Chrome 24 (though possibly from earlier), by nextgentech in comments, below:
$('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'));
}
});
。
这篇关于HTML5 / JS - 在div中显示多个文件输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!