如何在PHP中接收文本与客户端压缩文件并通过PHPMailer发送?
解决同时接收文本与压缩文件并通过PHPMailer发送的问题
先帮你理清之前的小疑问:你表单里写的action="upload.php"但uploadResized.php能运行,是因为客户端压缩后是把图片转成base64字符串,通过POST的image字段提交的——这不是传统的multipart/form-data文件上传方式,所以表单的enctype其实可以改成application/x-www-form-urlencoded(或者保留原配置也不影响,因为我们后续会用FormData统一提交)。只要把upload.php的内容换成对应处理逻辑就行。
下面是完整的实现方案,分三部分展开:
一、客户端表单与压缩逻辑调整
先修改HTML表单,添加文本输入框,同时确保压缩后的图片和文本一起提交到upload.php:
<form method="post" action="upload.php"> <input type="text" name="user_message" placeholder="请输入文本内容" required> <input type="file" id="image_upload" accept="image/*" multiple> <button type="submit">提交</button> </form> <script> // 拦截表单提交,先完成图片压缩再发送请求 document.querySelector('form').addEventListener('submit', async function(e) { e.preventDefault(); const fileInput = document.getElementById('image_upload'); const userMessage = document.querySelector('[name="user_message"]').value; const compressedImages = []; // 批量处理选中的图片 for (const file of fileInput.files) { const resizedBase64 = await resizeImage(file); compressedImages.push(resizedBase64); } // 用FormData封装文本和压缩后的图片数组 const formData = new FormData(); formData.append('user_message', userMessage); compressedImages.forEach((img, index) => { formData.append(`compressed_images[]`, img); }); // 发送请求到upload.php fetch('upload.php', { method: 'POST', body: formData }).then(response => response.text()) .then(result => alert(result)) .catch(error => console.error('提交出错:', error)); }); // 图片压缩核心函数(基于Canvas实现) function resizeImage(file) { return new Promise((resolve, reject) => { const img = new Image(); img.src = URL.createObjectURL(file); img.onload = () => { const canvas = document.createElement('canvas'); const maxWidth = 800; // 自定义压缩后的最大宽度 let width = img.width; let height = img.height; // 等比例缩放图片 if (width > maxWidth) { height *= maxWidth / width; width = maxWidth; } canvas.width = width; canvas.height = height; const ctx = canvas.getContext('2d'); ctx.drawImage(img, 0, 0, width, height); // 转成base64格式,质量0.8可根据需求调整 const base64 = canvas.toDataURL('image/jpeg', 0.8); resolve(base64); }; img.onerror = reject; }); } </script>
二、PHP端接收与邮件发送逻辑(upload.php)
这里我们会接收POST过来的文本和压缩图片,将图片转成临时文件后,用PHPMailer发送邮件:
<?php use PHPMailer\PHPMailer\PHPMailer; use PHPMailer\PHPMailer\Exception; // 引入PHPMailer(确保已通过Composer安装或手动引入文件) require 'vendor/autoload.php'; // 1. 接收并验证文本内容 $userMessage = $_POST['user_message'] ?? ''; if (empty($userMessage)) { die('请输入文本内容'); } // 2. 接收并处理压缩后的图片数组 $compressedImages = $_POST['compressed_images'] ?? []; if (empty($compressedImages)) { die('请选择要上传的图片'); } // 把base64图片转成临时文件,用于邮件附件 $attachments = []; foreach ($compressedImages as $index => $base64Img) { // 去除base64前缀 $imgData = str_replace('data:image/jpeg;base64,', '', $base64Img); $imgData = str_replace(' ', '+', $imgData); $decodedImg = base64_decode($imgData); // 创建系统临时文件 $tempFile = tempnam(sys_get_temp_dir(), 'compressed_img_') . '.jpg'; file_put_contents($tempFile, $decodedImg); $attachments[] = [ 'path' => $tempFile, 'name' => '压缩图片_' . ($index + 1) . '.jpg' ]; } // 3. 初始化PHPMailer并发送邮件 $mail = new PHPMailer(true); try { // SMTP服务器配置(替换成你的邮箱信息) $mail->SMTPDebug = 0; // 调试模式:0=关闭,2=开启 $mail->isSMTP(); $mail->Host = 'smtp.example.com'; $mail->SMTPAuth = true; $mail->Username = 'your_email@example.com'; $mail->Password = 'your_email_password'; // 注意:如果是QQ/163邮箱,需要用授权码 $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS; $mail->Port = 465; // 收件人配置 $mail->setFrom('your_email@example.com', '网站用户'); $mail->addAddress('recipient@example.com', '收件人名称'); // 邮件内容 $mail->isHTML(true); $mail->Subject = '用户提交的内容与压缩图片'; $mail->Body = '<h3>用户输入内容:</h3><p>' . nl2br(htmlspecialchars($userMessage)) . '</p>'; $mail->AltBody = '用户输入内容:' . PHP_EOL . $userMessage; // 添加附件 foreach ($attachments as $attachment) { $mail->addAttachment($attachment['path'], $attachment['name']); } $mail->send(); echo '提交成功,邮件已发送!'; // 清理临时文件 foreach ($attachments as $attachment) { unlink($attachment['path']); } } catch (Exception $e) { echo "提交失败:{$mail->ErrorInfo}"; // 异常情况下也清理临时文件 foreach ($attachments as $attachment) { if (file_exists($attachment['path'])) { unlink($attachment['path']); } } } ?>
补充说明
- PHPMailer安装:可以通过Composer执行
composer require phpmailer/phpmailer安装,或者手动下载PHPMailer的源码文件并引入。 - 临时文件处理:用
tempnam创建的临时文件会存在系统临时目录,发送完邮件后立即删除,避免服务器积累无用文件。 - 邮箱配置:不同邮箱的SMTP地址、端口和授权方式不同,比如QQ邮箱需要开启SMTP服务并使用授权码作为密码。
内容的提问来源于stack exchange,提问作者Daniel Stappenbeck
相关产品推荐
相关产品推荐

