如何使用 HTTP POST 选择和上传带有 HTML 和PHP 的多个文件?
在本文中,我们将看看如何使用 HTML 和PHP上传多个文件。多张图片上传允许用户一次选择多个文件并将所有文件上传到服务器。
index.html创建一个简单的 HTML 页面来选择多个文件并提交到服务器上上传文件。此处,HTML 文件包含使用 POST 方法选择和上传文件的表单。
HTML
Select and upload multiple
files to the server
PHP
$value) {
$file_tmpname = $_FILES['files']['tmp_name'][$key];
$file_name = $_FILES['files']['name'][$key];
$file_size = $_FILES['files']['size'][$key];
$file_ext = pathinfo($file_name, PATHINFO_EXTENSION);
// Set upload file path
$filepath = $upload_dir.$file_name;
// Check file type is allowed or not
if(in_array(strtolower($file_ext), $allowed_types)) {
// Verify file size - 2MB max
if ($file_size > $maxsize)
echo "Error: File size is larger than the allowed limit.";
// If file with name already exist then append time in
// front of name of the file to avoid overwriting of file
if(file_exists($filepath)) {
$filepath = $upload_dir.time().$file_name;
if( move_uploaded_file($file_tmpname, $filepath)) {
echo "{$file_name} successfully uploaded
";
}
else {
echo "Error uploading {$file_name}
";
}
}
else {
if( move_uploaded_file($file_tmpname, $filepath)) {
echo "{$file_name} successfully uploaded
";
}
else {
echo "Error uploading {$file_name}
";
}
}
}
else {
// If file extension not valid
echo "Error uploading {$file_name} ";
echo "({$file_ext} file type is not allowed)
";
}
}
}
else {
// If no files selected
echo "No files selected.";
}
}
?>
上传文件。 PHP file_upload。 PHP脚本将处理文件上传并显示上传状态。
PHP
$value) {
$file_tmpname = $_FILES['files']['tmp_name'][$key];
$file_name = $_FILES['files']['name'][$key];
$file_size = $_FILES['files']['size'][$key];
$file_ext = pathinfo($file_name, PATHINFO_EXTENSION);
// Set upload file path
$filepath = $upload_dir.$file_name;
// Check file type is allowed or not
if(in_array(strtolower($file_ext), $allowed_types)) {
// Verify file size - 2MB max
if ($file_size > $maxsize)
echo "Error: File size is larger than the allowed limit.";
// If file with name already exist then append time in
// front of name of the file to avoid overwriting of file
if(file_exists($filepath)) {
$filepath = $upload_dir.time().$file_name;
if( move_uploaded_file($file_tmpname, $filepath)) {
echo "{$file_name} successfully uploaded
";
}
else {
echo "Error uploading {$file_name}
";
}
}
else {
if( move_uploaded_file($file_tmpname, $filepath)) {
echo "{$file_name} successfully uploaded
";
}
else {
echo "Error uploading {$file_name}
";
}
}
}
else {
// If file extension not valid
echo "Error uploading {$file_name} ";
echo "({$file_ext} file type is not allowed)
";
}
}
}
else {
// If no files selected
echo "No files selected.";
}
}
?>
输出:
- 上传文件前:
- 上传文件后:
PHP是一种专门为 Web 开发设计的服务器端脚本语言。您可以按照此PHP教程和PHP示例从头开始学习PHP 。