我得到了上传多个文件的代码,但现在我不知道如何上传包含多个文件的文件夹以及包含更多文件的子文件夹。 ETC 如您所见,我现在正在使用 javscript 获取文件并使用 php 处理和保存文件,文件大小约为 2MB 我试图用 foreach 得到 $_Folder 但它对我不起作用:/
Index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Upload Files</title>
</head>
<body>
<form method="post" enctype="multipart/form-data">
<input type="file" name="files[]" multiple>
<input type="submit" value="Upload File" name="submit">
</form>
<script src="upload.js"></script>
</body>
</html>
进程.php
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (isset($_FILES['files'])) {
$errors = [];
$path = 'uploads/';
$extensions = ['jpg', 'jpeg', 'png', 'gif'];
$all_files = count($_FILES['files']['tmp_name']);
for ($i = 0; $i < $all_files; $i++) {
$file_name = $_FILES['files']['name'][$i];
$file_tmp = $_FILES['files']['tmp_name'][$i];
$file_type = $_FILES['files']['type'][$i];
$file_size = $_FILES['files']['size'][$i];
$file_ext = strtolower(end(explode('.', $_FILES['files']['name'][$i])));
$file = $path . $file_name;
if (!in_array($file_ext, $extensions)) {
$errors[] = 'Extension not allowed: ' . $file_name . ' ' . $file_type;
}
if ($file_size > 2097152) {
$errors[] = 'File size exceeds limit: ' . $file_name . ' ' . $file_type;
}
if (empty($errors)) {
move_uploaded_file($file_tmp, $file);
}
}
if ($errors) print_r($errors);
}
}
上传.js
const url = 'process.php';
const form = document.querySelector('form');
form.addEventListener('submit', e => {
e.preventDefault();
const files = document.querySelector('[type=file]').files;
const formData = new FormData();
for (let i = 0; i < files.length; i++) {
let file = files[i];
formData.append('files[]', file);
}
fetch(url, {
method: 'POST',
body: formData
}).then(response => {
console.log(response);
});
});
期待上传这样的东西
Upload:
-(1Folder)
--Image.png
--Imagen.jpg
--(2Folder)
---Image2.png
--(3Folder)
---Image3.jpg
--Imagen.gif
最佳答案
在现代 Chrome、Firefox 和 Edge 中,您可以设置一个 html 属性,webkitdiretory
让文件输入变成目录选择窗口。如果您在选择文件夹后还使用了 multiple
属性,则所有内容(以及子文件夹中的内容)都将位于 .files
列表中
<input type="file" webkitdirectory multiple>
然后您只需使用相同的代码来包含所有要上传的文件。
现在,如果您想保留文件夹结构,您还必须包括 webkitRelativePath
它包含您选择的文件夹中该文件的相对路径。并使用该路径在服务器上创建文件夹。
for (let i = 0; i < files.length; i++) {
let file = files[i];
let fileParamName = `file${i}`;
let filePathParamName = `filepath${i}`;
formData.append(fileParamName, file);
formData.append(filePathParamName,file.webkitRelativePath);
}
然后在服务器上使用 filePathParamName 创建目录结构并将文件移动到它:
//Just for example
//make sure to used sanitized data in production
$folderpath = $path.dirname($_POST["filepath23"]);
$file = $path.$_POST["filepath23"];
$file_tmp = $_FILES["file23"]["tmp_name"];
//third option is for recursive folder creation (make subfolders)
mkdir($path,0644,true);
move_uploaded_file($file_tmp, $file)
对于一种更简单的方法,您可以将所有文件放入 javascript 中的一个 zip 文件中,然后只需上传单个 zip 文件并在服务器上解压缩。 Using JSZip和 PHP ZipArchive class :
var zip = new JSZip();
for (let i = 0; i < files.length; i++) {
let file = files[i];
zip.file(file.webkitRelativePath, file);
}
zip.generateAsync({type:"blob"})
.then(function(content) {
formData.append("folderzip",content);
fetch(url, {
method: 'POST',
body: formData
}).then(response => {
console.log(response);
});
});
然后在php中解压文件夹到你想要的地方:
move_uploaded_file($file_tmp, $path);
$zip = new ZipArchive();
if($zip->open($path)){
$zip->extractTo($somepath);
$zip->close();
//delete zip file
unlink($path);
}
使用 webkitRelativePath 的文件列表的客户端演示:
var output = document.querySelector("#output");
document.querySelector("input").onchange = function() {
var files = this.files;
for (file of files) {
output.insertAdjacentHTML('beforeend', `<div>${file.webkitRelativePath}</div>`);
}
}
<input type="file" webkitdirectory multiple>
<div id="output"></div>
关于javascript - 如何上传包含文件的完整文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57749112/