引言
准备工作
在开始之前,请确保以下准备工作已完成:
- 安装并配置PHP环境。
- 准备一个HTML页面作为iframe的容器。
- 准备一个PHP脚本用于处理图片上传。
HTML表单设计
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="image" accept="image/*">
<input type="submit" value="Upload Image">
</form>
PHP脚本编写
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_FILES['image'])) {
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["image"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));
// 检查文件是否是图片
$check = getimagesize($_FILES["image"]["tmp_name"]);
if ($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
// 检查文件是否已存在
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// 检查文件大小
if ($_FILES["image"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// 允许特定格式的文件
if ($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif") {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// 检查是否上传成功
if ($uploadOk == 1) {
if (move_uploaded_file($_FILES["image"]["tmp_name"], $target_file)) {
echo "The file " . htmlspecialchars(basename($_FILES["image"]["name"])) . " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
}
?>
iframe嵌入
<iframe id="imageFrame" src="" width="100%" height="500px" frameborder="0"></iframe>
// 上传成功后,将图片URL赋值给iframe的src属性
if ($uploadOk == 1 && move_uploaded_file($_FILES["image"]["tmp_name"], $target_file)) {
echo "The file " . htmlspecialchars(basename($_FILES["image"]["name"])) . " has been uploaded.";
echo "<script>document.getElementById('imageFrame').src='" . $target_file . "';</script>";
} else {
echo "Sorry, there was an error uploading your file.";
}