上传一个小于30k的图片文件,保存在上传表单文件同一路径下的img文件下,并且要求图片输出至浏览器
时间: 2023-12-03 10:42:28 浏览: 78
以下是 PHP 代码示例:
```php
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (isset($_FILES['image'])) {
$maxFileSize = 30 * 1024; // 30 KB
$allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];
$error = $_FILES['image']['error'];
$size = $_FILES['image']['size'];
$type = $_FILES['image']['type'];
$tmpName = $_FILES['image']['tmp_name'];
if ($error !== UPLOAD_ERR_OK) {
echo 'Error uploading file.';
exit;
}
if ($size > $maxFileSize) {
echo 'File size exceeds maximum limit.';
exit;
}
if (!in_array($type, $allowedTypes)) {
echo 'Invalid file type.';
exit;
}
$uploadDir = __DIR__ . '/img/';
$uploadPath = $uploadDir . basename($_FILES['image']['name']);
if (!move_uploaded_file($tmpName, $uploadPath)) {
echo 'Error saving file.';
exit;
}
header('Content-Type: ' . $type);
echo file_get_contents($uploadPath);
exit;
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Upload Image</title>
</head>
<body>
<form method="post" enctype="multipart/form-data">
<input type="file" name="image">
<button type="submit">Upload</button>
</form>
</body>
</html>
```
这段代码会检查上传的文件是否符合要求(小于30 KB,类型为 JPEG、PNG 或 GIF),并将文件保存在 `img` 文件夹中。如果上传成功,它会将图片输出至浏览器。
阅读全文