...多个文件输入... FileList 被覆盖...
实际上,这就是带有属性的 HTML文件输入的multiple
工作方式——用户必须使用 shift 或 control click 一次选择他们想要上传的所有文件。如果用户第二次操作相同的文件输入上传过程,则之前选择的任何内容都将被丢弃,并且只有最近的选择保留在FileList中。
但是没有办法让用户多次上传文件。
为了让您的站点用户多次使用 HTML 文件输入元素并保留所有先前的选择,您需要将每次使用文件元素时收到的文件(base64 数据)写入隐藏的表单元素。
例如:
<form action="process.php" method="post" name="uploadform" enctype="multipart/form-data">
// other form elements if needed
<input type="submit">
</form>
<!-- outside the form, you don't want to upload this one -->
<input type="file" id="upfiles" name="upfiles">
<script>
document.getElementById('upfiles').addEventListener('change', handle_files, false);
function handle_files(evt) {
var ff = document.forms['uploadform'];
var files = evt.target.files;
for ( var i = 0, file; file = files[i]; i++ ) {
var reader = new FileReader();
reader.onload = (function(file) {
return function (ufile) {
var upp = document.createElement('input');
upp['type'] = 'hidden';
upp['name'] = +new Date + '_upfile_' + file.name.replace(/(\[|\]|&|~|!|\(|\)|#|\|\/)/ig, '');
upp.value = ufile.target.result;
ff.appendChild(upp);
}
}(file));
reader.readAsDataURL(file);
}
}
</script>
接下来,您需要编写一个在服务器上运行的脚本来处理隐藏的 base64 字段。如果使用 PHP,您可以:
<?php
$path = 'path/to/file/directory/';
// this is either:
// - the absolute path, which is from server root
// to the files directory, or
// - the relative path, which is from the directory
// the PHP script is in to the files directory
foreach ( $_POST as $key => $value ) { // loop over posted form vars
if ( strpos($key, '_upfile_') ) { // find the file upload vars
$value = str_replace(' ', '+', $value); // url encode
file_put_contents($path.$key, base64_decode($value));
// convert data to file in files directory with upload name ($key)
}
}
?>