如何将input type="file"多文件转为Resend要求的string/buffer格式?
解决Resend邮件附件JSON传输格式问题
前端处理:将文件转为Base64字符串(适配JSON传输)
因为JSON无法直接传输File对象,需要把文件转成Base64字符串(属于Resend支持的string格式范畴),再和其他表单数据一起打包成JSON发送:
document.getElementById('contact-form').addEventListener('submit', async (e) => { e.preventDefault(); // 收集基础表单数据 const payload = { from: 'Acme <onboarding@resend.dev>', to: ['delivered@resend.dev'], subject: document.getElementById('subject').value, text: document.getElementById('message').value, attachments: [] }; // 获取多文件选择的结果 const fileInput = document.getElementById('file-attachments'); const files = fileInput.files; // 遍历文件,转成Base64字符串 for (let i = 0; i < files.length; i++) { const file = files[i]; const base64Content = await new Promise((resolve) => { const reader = new FileReader(); reader.onloadend = () => { // 去掉dataURL前缀,只保留纯Base64字符串 resolve(reader.result.split(',')[1]); }; reader.readAsDataURL(file); }); payload.attachments.push({ filename: file.name, content: base64Content }); } // 发送JSON格式的POST请求到后端 await fetch('/api/send-email', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload) }); });
后端处理:将Base64转为Buffer(适配Resend要求)
后端接收JSON后,把Base64字符串转成Resend需要的Buffer格式,再调用API发送邮件:
const express = require('express'); const { Resend } = require('resend'); const app = express(); app.use(express.json()); const resend = new Resend('你的Resend API密钥'); app.post('/api/send-email', async (req, res) => { try { // 处理附件:Base64字符串转Buffer const processedAttachments = req.body.attachments.map(att => ({ filename: att.filename, content: Buffer.from(att.content, 'base64') })); // 调用Resend发送邮件 const data = await resend.emails.send({ from: req.body.from, to: req.body.to, subject: req.body.subject, text: req.body.text, attachments: processedAttachments }); res.status(200).json(data); } catch (error) { res.status(400).json({ error: error.message }); } }); app.listen(3000, () => console.log('服务运行在3000端口'));
关键注意点
- 前端转Base64时必须去掉
data:xxx;base64,前缀,否则后端转Buffer会失败 - 后端通过
Buffer.from(base64Str, 'base64')完成格式转换,完全符合Resend的参数要求 - 整个流程保持JSON传输方式,和你现有代码逻辑兼容
内容的提问来源于stack exchange,提问作者Aspiring Dev 23000
相关产品推荐
相关产品推荐

