我有一个带有上传字段的表单,允许用户选择多个文件。但是,我需要能够允许用户从文件夹 1 中选择文件 1,然后从文件夹 2 中选择文件 2,依此类推。
目前,当用户从文件夹 1 选择文件 1 然后点击“打开”时,选择窗口关闭(将用户留在我的表单上)。然后,如果用户从文件夹 2 中选择文件 2 并点击“打开”按钮,文件 1 将被删除,只留下文件 2。
基本上,用户无法选择多个文件,除非它们都位于同一位置。选择文件 2 后,有没有办法让文件 1 保持选中状态?
最佳答案
这个怎么样?
该解决方案使用 HTML、jQuery/Javascript 和 PHP(用于服务器端处理此数据)。这个想法是: 1.) HTML 表单:包括一个“浏览”按钮,允许用户选择多个文件(在一个目录中)。 2.) jQuery:在表单中创建新按钮的选项允许用户选择多个文件(在不同的目录中——甚至实际上是同一个文件!),具有“无限”创建新按钮的能力。 3.) PHP:作为奖励,我考虑了将数据很好地打包以便服务器端处理。
这是 HTML 表单的样子(我为可点击对象使用了一个找到的图标,但您可以轻松地将其替换为您选择的图形)。
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" enctype='multipart/form-data'>
Select files: <br/>
<input type='file' name='files0[]' id="files0" multiple><br/><br/><br/>
<span style="font-size: 10pt;">Click "+" for more files
<i id="more_files" class="general foundicon-plus" style="color: blue;cursor: pointer;"></i></span>
<br/><br/><br/>
<input type="submit" name="submit" value="Submit">
</form>
这是在事件被触发后创建一个新的“浏览”按钮的 jQuery/Javascript(这甚至将它放在最后一个“浏览”按钮之后!):
<script type="text/javascript">
//jQuery
$(document).ready(function() {
$(document).on('click','#more_files', function() {
var numOfInputs = 1;
while($('#files'+numOfInputs).length) { numOfInputs++; }//once this loop breaks, numOfInputs is greater than the # of browse buttons
$("<input type='file' multiple/>")
.attr("id", "files"+numOfInputs)
.attr("name", "files"+numOfInputs+"[]")
.insertAfter("#files"+(numOfInputs-1));
$("<br/>").insertBefore("#files"+numOfInputs);
});
});
</script>
<script>
//vanilla javascript version
var location = document.getElementById("fileBrowsers");
var br = document.createElement("BR");
location.appendChild(br);
var input = document.createElement("input");
input.type = "file";
input.name = "files"+numOfInputs+"[]";
input.id = "files"+numOfInputs;
input.multiple = true;
location.appendChild(input);
</script>
最后,可能也是最重要的,如何以熟悉的格式包装服务器上的数据:
<?php
if(isset($_POST['submit']) && !empty($_FILES)) {
$files = array();
$files = $_FILES['files0'];
//var_dump($files);//this array will match the structure of $_FILES['browser']
//Iterate through each browser button
$browserIterator = 1;
while(isset($_FILES['files'.$browserIterator])) {
//Files have same attribute structure, so grab each attribute and append data for each attribute from each file
foreach($_FILES['files'.$browserIterator] as $attr => $values) {//get each attribute
foreach($_FILES['files'.$browserIterator][$attr] as $fileValue) {//get each value from attribute
$files[$attr][] = $fileValue;//append value
}
}
$browserIterator++;
}
//Use $files like you would use $_FILES['browser'] -- It is as though all files came from one browser button!
$fileIterator = 0;
while($fileIterator < count($files['name'])) {
echo $files['name'][$fileIterator]."<br/>";
$fileIterator++;
}
}
?>
更新说明:jQuery 脚本和原始 Javascript 实现了相同的目标。我遇到了一个需要 Vanilla 版本的问题。 您只需要其中之一。
关于从不同文件夹上传 HTML 多个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24889270/