PHP Forma 表单 多文件预览 缩略图显示 的上传表单

PHP Forma阿木 发布于 1 天前 2 次阅读


PHP 表单多文件上传与预览功能实现

在Web开发中,多文件上传与预览功能是常见的需求,尤其是在图片、文档等文件的处理上。本文将围绕PHP技术,详细讲解如何实现一个基于HTML表单的多文件上传与预览功能,并展示如何使用PHP来处理文件上传,生成缩略图,并在页面上显示预览效果。

1. 前端HTML表单设计

我们需要设计一个HTML表单,允许用户选择多个文件进行上传。以下是基本的HTML表单代码:

html

多文件上传与预览

选择文件:

在这个表单中,`` 元素的 `multiple` 属性允许用户选择多个文件。`name="fileUpload[]"` 确保所有选中的文件都会被发送到服务器。

2. PHP后端处理

接下来,我们需要编写PHP代码来处理文件上传,并生成缩略图。

2.1 文件上传处理

我们需要在服务器上创建一个处理文件上传的PHP脚本,例如 `upload.php`。

php
$name) {
$tmpName = $_FILES['fileUpload']['tmp_name'][$key];
$error = $_FILES['fileUpload']['error'][$key];
$type = $_FILES['fileUpload']['type'][$key];
$size = $_FILES['fileUpload']['size'][$key];

// 检查是否有错误
if ($error !== UPLOAD_ERR_OK) {
echo "文件上传错误:{$name}";
continue;
}

// 检查文件类型和大小
if (!in_array($type, $allowedTypes) || $size > $maxSize) {
echo "文件类型或大小不正确:{$name}";
continue;
}

// 生成新文件名
$newName = uniqid() . '.' . pathinfo($name, PATHINFO_EXTENSION);
$uploadPath = $uploadDir . $newName;

// 移动文件到上传目录
if (move_uploaded_file($tmpName, $uploadPath)) {
echo "文件上传成功:{$name}";
// 生成缩略图
createThumbnail($uploadPath, $uploadPath, 100, 100);
} else {
echo "文件上传失败:{$name}";
}
}
}

// 生成缩略图的函数
function createThumbnail($sourcePath, $destinationPath, $width, $height) {
list($originalWidth, $originalHeight) = getimagesize($sourcePath);
$ratio = min($width / $originalWidth, $height / $originalHeight);
$newWidth = $originalWidth $ratio;
$newHeight = $originalHeight $ratio;

$sourceImage = imagecreatefromjpeg($sourcePath);
$destinationImage = imagecreatetruecolor($width, $height);

// 调整图片大小
imagecopyresampled($destinationImage, $sourceImage, 0, 0, 0, 0, $newWidth, $newHeight, $originalWidth, $originalHeight);

// 保存缩略图
imagejpeg($destinationImage, $destinationPath);
imagedestroy($sourceImage);
imagedestroy($destinationImage);
}
?>

在这个脚本中,我们首先检查是否有文件被上传,然后遍历每个文件,检查是否有错误,是否是允许的文件类型和大小。如果一切正常,我们将文件移动到服务器上的上传目录,并调用 `createThumbnail` 函数来生成缩略图。

2.2 生成缩略图

`createThumbnail` 函数使用GD库来处理图像。它首先获取原始图像的尺寸,然后计算缩略图的新尺寸,并创建一个新的图像资源。接着,使用 `imagecopyresampled` 函数将原始图像调整到新的尺寸,并保存到目标路径。

3. 显示预览效果

为了在页面上显示预览效果,我们可以在HTML表单中添加一个容器来显示缩略图。以下是修改后的HTML代码:

html

多文件上传与预览

选择文件:

document.querySelector('form').addEventListener('change', function() {
var previewContainer = document.getElementById('previewContainer');
previewContainer.innerHTML = '';

var files = this.files;
for (var i = 0; i < files.length; i++) {
var reader = new FileReader();
reader.onload = function(e) {
var img = document.createElement('img');
img.src = e.target.result;
img.style.width = '100px';
img.style.height = '100px';
previewContainer.appendChild(img);
};
reader.readAsDataURL(files[i]);
}
});

在这个脚本中,我们监听表单的 `change` 事件,当用户选择文件后,读取每个文件的内容,并创建一个 `img` 元素来显示缩略图。

4. 总结

通过以上步骤,我们实现了一个基于PHP的多文件上传与预览功能。用户可以选择多个文件,服务器端会处理上传,生成缩略图,并在页面上显示预览效果。这个功能在图片、文档等文件的上传场景中非常有用,可以提供更好的用户体验。