javascript,// 使用FormData对象和XMLHttpRequest上传图片,并在PHP端进行压缩处理后显示。,
“
Ajax 上传图片到 PHP 并压缩图片显示
一、前端部分(HTML + JavaScript)
我们需要创建一个文件上传的表单,以及用于显示图片的元素。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Ajax Upload and Compress Image</title> </head> <body> <h1>Upload an Image</h1> <form id="uploadForm"> <input type="file" id="imageInput" name="image" accept="image/"> <button type="button" onclick="uploadImage()">Upload</button> </form> <br> <h2>Compressed Image:</h2> <img id="compressedImage" src="" alt="Compressed Image" style="max-width: 500px; display: none;"> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script src="upload.js"></script> </body> </html>
2. JavaScript 代码(upload.js)
使用 Ajax 将图片上传到服务器,并在上传成功后显示压缩后的图片。
function uploadImage() { var formData = new FormData(); var imageInput = document.getElementById('imageInput'); var imageFile = imageInput.files[0]; if (imageFile) { formData.append('image', imageFile); $.ajax({ url: 'upload.php', type: 'POST', data: formData, processData: false, contentType: false, success: function(response) { if (response.success) { $('#compressedImage').attr('src', response.compressedImageUrl); $('#compressedImage').show(); } else { alert('Error uploading image'); } }, error: function() { alert('An error occurred while uploading the image'); } }); } else { alert('Please select an image to upload'); } }
二、后端部分(PHP)
1. PHP 代码(upload.php)
处理图片上传,并进行压缩处理,然后返回压缩后的图片 URL。
<?php if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_FILES['image'])) { $targetDir = "uploads/"; $targetFile = $targetDir . basename($_FILES["image"]["name"]); $imageFileType = strtolower(pathinfo($targetFile, PATHINFO_EXTENSION)); // Check if image file is a actual image or fake image $check = getimagesize($_FILES["image"]["tmp_name"]); if ($check !== false) { $allowedTypes = array("jpg", "jpeg", "png", "gif"); if (in_array($imageFileType, $allowedTypes)) { // Move uploaded file to target directory if (move_uploaded_file($_FILES["image"]["tmp_name"], $targetFile)) { // Compress the image $compressedImagePath = compressImage($targetFile); if ($compressedImagePath) { echo json_encode([ 'success' => true, 'compressedImageUrl' => $compressedImagePath ]); } else { echo json_encode([ 'success' => false, 'message' => 'Failed to compress image' ]); } } else { echo json_encode([ 'success' => false, 'message' => 'Failed to move uploaded file' ]); } } else { echo json_encode([ 'success' => false, 'message' => 'Only JPG, JPEG, PNG & GIF files are allowed' ]); } } else { echo json_encode([ 'success' => false, 'message' => 'File is not an image' ]); } } else { echo json_encode([ 'success' => false, 'message' => 'No file uploaded' ]); } function compressImage($sourcePath) { $quality = 70; // Compression quality (0-100) list($width, $height) = getimagesize($sourcePath); $newWidth = $width / 2; $newHeight = $height / 2; $imageCreateFunction = 'imagecreatefrom' . substr(strtolower(pathinfo($sourcePath, PATHINFO_EXTENSION)), 0, 3); $image = $imageCreateFunction($sourcePath); $newImage = imagecreatetruecolor($newWidth, $newHeight); imagecopyresampled($newImage, $image, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height); imagedestroy($image); $compressedImagePath = 'uploads/compressed_' . basename($sourcePath); imagejpeg($newImage, $compressedImagePath, $quality); imagedestroy($newImage); return $compressedImagePath; } ?>
三、目录结构说明
确保你的项目目录结构如下:
project/ ├── index.html ├── upload.js ├── upload.php └── uploads/ (directory for storing uploaded images)
四、相关问题与解答
问题 1:如何确保上传的图片是合法的图片格式?
解答:在 PHP 端,我们使用了getimagesize
函数来检查上传的文件是否为有效的图像文件,我们还限制了允许上传的文件类型为常见的图片格式(如 JPG、JPEG、PNG、GIF),在前端,可以通过文件输入的accept
属性来限制用户选择的文件类型,但这只是一种客户端的验证,服务器端仍需进行严格的验证。
解答:在 PHP 的compressImage
函数中,我们使用imagejpeg
函数的第三个参数来设置压缩质量,这个参数的取值范围是 0 到 100,数值越小,压缩后的图片质量越低,文件大小也越小,你可以根据实际需求调整这个参数的值来平衡图片质量和文件大小,将质量设置为 50 可以得到中等压缩效果的图片。