如何用Fetch同时实现文件上传服务器与Google Sheets表单提交?
解决方案
1. 给表单添加文件上传字段
在你的HTML表单里加入文件输入控件,限定只接受PDF和JPG格式:
<input type="file" name="uploadedFile" accept=".pdf,.jpg" required>
2. 修改表单提交逻辑
替换原有的表单提交监听代码,让它同时处理Google Sheets数据提交和服务器文件上传:
const scriptURL = '...'; // 你的Google Sheets脚本地址 const uploadServerURL = 'https://你的服务器上传接口'; // 换成你自己的服务器上传地址 const form = document.forms['submit-to-google-sheet']; form.addEventListener('submit', e => { e.preventDefault(); // 生成时间戳 document.getElementById('timestamp').value = new Date().toLocaleString('uk-UA', { year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit' }); // 创建包含所有表单数据的FormData对象 const formData = new FormData(form); // 同时发起两个异步请求 Promise.all([ // 请求1:提交数据到Google Sheets fetch(scriptURL, { method: 'POST', body: formData }), // 请求2:上传文件到服务器 fetch(uploadServerURL, { method: 'POST', body: formData }) ]) .then(([sheetRes, uploadRes]) => { // 检查两个请求是否都成功 if (!sheetRes.ok || !uploadRes.ok) { throw new Error('部分请求失败'); } console.log('Google Sheets提交成功', sheetRes); console.log('文件上传成功', uploadRes); // 显示成功状态 document.getElementById('contactForm').style.display = 'none'; document.getElementById('success-message').style.display = 'block'; }) .catch(error => { console.error('错误详情:', error.message); alert('提交出错,请稍后重试。'); }); });
额外说明
Promise.all()会等待两个请求都完成后再执行后续逻辑,避免一个操作失败导致另一个无响应- 如果Google Sheets不需要接收文件数据,可以复制一份FormData并删除文件字段后再提交:
const sheetFormData = new FormData(form); sheetFormData.delete('uploadedFile'); // 移除文件字段 // 用sheetFormData作为body发送到scriptURL - 你的服务器端需要配置对应的上传接口,支持接收
multipart/form-data类型的请求,并实现文件存储的逻辑
内容的提问来源于stack exchange,提问作者Bohdan
相关产品推荐
相关产品推荐

