4. 编写程序,实现多文件上传。表单页面可以考虑用JQUERY实现不固定数量的文件上传框。文件名multiplefiles.html、upload.php。利用函数封装多文件上传操作,以实现函数的重复利用。(可以在网上搜索一下代码)
时间: 2023-06-15 12:03:26 浏览: 162
web页面多选上传文件的实现(浏览器-打开文件-可选多个文件来上传).源代码
multiplefiles.html:
```html
<!DOCTYPE html>
<html>
<head>
<title>多文件上传</title>
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
<script>
$(function(){
$("#addFile").click(function(){
var fileInput = '<input type="file" name="file[]" /><br/>';
$("#fileContainer").append(fileInput);
});
});
</script>
</head>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
<div id="fileContainer">
<input type="file" name="file[]" /><br/>
</div>
<input type="button" id="addFile" value="添加文件" />
<input type="submit" value="上传" />
</form>
</body>
</html>
```
upload.php:
```php
<?php
function uploadFiles($files, $uploadDir) {
if(!file_exists($uploadDir)) {
mkdir($uploadDir, 0777, true);
}
$uploadedFiles = array();
$errors = array();
foreach($files['name'] as $key => $name) {
if($files['error'][$key] === UPLOAD_ERR_OK) {
$tmpName = $files['tmp_name'][$key];
$ext = pathinfo($name, PATHINFO_EXTENSION);
$newName = uniqid('file_').'.'.$ext;
$dest = $uploadDir.'/'.$newName;
if(move_uploaded_file($tmpName, $dest)) {
$uploadedFiles[] = $newName;
} else {
$errors[] = '无法移动文件 '.$name.'.';
}
} else {
$errors[] = '上传文件 '.$name.' 出错:'.$files['error'][$key];
}
}
return array(
'uploadedFiles' => $uploadedFiles,
'errors' => $errors,
);
}
if(isset($_FILES['file'])) {
$uploadDir = 'uploads';
$result = uploadFiles($_FILES['file'], $uploadDir);
echo '<h2>上传结果</h2>';
if(!empty($result['uploadedFiles'])) {
echo '<p>上传成功的文件:</p>';
echo '<ul>';
foreach($result['uploadedFiles'] as $file) {
echo '<li>'.$file.'</li>';
}
echo '</ul>';
}
if(!empty($result['errors'])) {
echo '<p>上传失败的文件:</p>';
echo '<ul>';
foreach($result['errors'] as $error) {
echo '<li>'.$error.'</li>';
}
echo '</ul>';
}
}
?>
```
阅读全文