基于AWS Lambda与SES实现带文件上传的网站联系表单问询
Got it, let's walk through how to add file upload functionality to your existing AWS Lambda + SES contact form. I’ve built this exact setup before, so here’s a step-by-step breakdown with actionable code snippets:
First, you’ll need to adjust your form to support file uploads—plain JSON won’t work here, so we’ll use multipart/form-data encoding. Here’s a modified form example:
<form id="contactForm" enctype="multipart/form-data"> <input type="text" name="name" placeholder="Your Name" required> <input type="email" name="email" placeholder="Your Email" required> <textarea name="message" placeholder="Your Message" rows="4" required></textarea> <!-- Add file input with accepted types --> <input type="file" name="attachment" accept=".pdf,.doc,.docx,.jpg,.png" required> <button type="submit">Send Message</button> </form>
Next, update your frontend JavaScript to send the form as FormData instead of a JSON string:
document.getElementById('contactForm').addEventListener('submit', async (e) => { e.preventDefault(); const formData = new FormData(e.target); try { const response = await fetch('YOUR_LAMBDA_API_GATEWAY_ENDPOINT', { method: 'POST', body: formData }); const result = await response.json(); alert('Message sent successfully with attachment!'); e.target.reset(); } catch (error) { console.error('Submission error:', error); alert('Failed to send your message. Please try again later.'); } });
Lambda can’t natively parse multipart/form-data, so we’ll use the aws-lambda-multipart-parser package to handle file extraction. Here’s the updated Node.js function:
First, install the dependency:
npm install aws-lambda-multipart-parser
(You can either package this with your Lambda code or add it as a Lambda Layer for reusability.)
Then the Lambda code:
const AWS = require('aws-sdk'); const parser = require('aws-lambda-multipart-parser'); const ses = new AWS.SES({ region: 'YOUR_AWS_REGION' }); exports.handler = async (event) => { try { // Parse incoming multipart form data const formData = parser.parse(event); // Extract form fields and attached file const { name, email, message } = formData; const attachment = formData.files[0]; // Get the first uploaded file // Encode file content to Base64 (required for SES attachments) const fileBase64 = attachment.content.toString('base64'); // Build SES email parameters with attachment const emailParams = { Destination: { ToAddresses: ['YOUR_SITE_OWNER_EMAIL@example.com'] }, Message: { Body: { Text: { Data: `New contact form submission:\n\nName: ${name}\nEmail: ${email}\nMessage:\n${message}` } }, Subject: { Data: `Contact Form: ${name} sent a message with attachment` } }, Source: 'YOUR_VERIFIED_SES_EMAIL@example.com', Attachments: [ { Filename: attachment.filename, ContentType: attachment.contentType, Content: fileBase64 } ] }; // Send the email via SES await ses.sendEmail(emailParams).promise(); return { statusCode: 200, body: JSON.stringify({ success: true, message: 'Email sent with attachment' }) }; } catch (error) { console.error('SES send error:', error); return { statusCode: 500, body: JSON.stringify({ success: false, error: error.message }) }; } };
Make sure your Lambda execution role has permission to send emails via SES. Add this policy to the role:
{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": "ses:SendEmail", "Resource": "*" } ] }
Note: If you’re still in SES sandbox mode, both the sender and recipient emails must be verified in the AWS SES console.
- Submit the form with a valid file (match the
accepttypes in your HTML) - Check CloudWatch Logs for Lambda to debug any parsing or SES errors
- Verify the recipient inbox receives the email with the attached file
内容的提问来源于stack exchange,提问作者AynonT

