Google Apps Script文件上传成功后如何展示Toast提示?
解决方案
你无需修改后端code.gs代码,仅修改前端form.html代码即可实现上传完成后弹出Toast提示的效果,修改方式如下:
步骤1:新增Toast样式与DOM结构
在原代码的</form>闭合标签之后,插入以下代码:
<!-- Toast提示容器 --> <div id="toast" style="display: none; position: fixed; top: 20%; left: 50%; transform: translateX(-50%); background: #4CAF50; color: #fff; padding: 12px 24px; border-radius: 4px; box-shadow: 0 2px 12px rgba(0,0,0,0.2); z-index: 9999;"> 文件上传成功,感谢您的提交! </div>
步骤2:修改JS提交逻辑,控制Toast显示
将原有的<script>块的代码替换为以下内容,注意保留你自己的Web Apps部署链接:
const form = document.getElementById('form'); const toast = document.getElementById('toast'); // 显示Toast的通用方法 function showToast(isSuccess, msg) { toast.textContent = isSuccess ? '文件上传成功,感谢您的提交!' : msg; toast.style.background = isSuccess ? '#4CAF50' : '#f44336'; toast.style.display = 'block'; setTimeout(() => { toast.style.display = 'none'; // 重置Toast默认状态 toast.textContent = '文件上传成功,感谢您的提交!'; toast.style.background = '#4CAF50'; }, 3000); } form.addEventListener('submit', e => { e.preventDefault(); // 提交前先校验是否选择了文件 if (!form.file.files[0]) { showToast(false, '请先选择要上传的文件'); return; } const file = form.file.files[0]; const fr = new FileReader(); fr.readAsArrayBuffer(file); fr.onload = f => { // 此处替换为你自己的Web Apps部署链接 const url = "https://script.google.com/macros/s/AKfycbxr8nvfm1f4dy1NxOqHxNJlVzQmkAmSPjaqgtFwZ5KHVA1Zfxx0vLllFEAGGZF0yH_5/exec"; const qs = new URLSearchParams({filename: form.filename.value || file.name, mimeType: file.type}); fetch(`${url}?${qs}`, {method: "POST", body: JSON.stringify([...new Int8Array(f.target.result)])}) .then(res => res.json()) .then(e => { showToast(true); form.reset(); // 上传成功后重置表单 }) .catch(err => { showToast(false, '上传失败,请稍后重试'); console.log(err); }); } });
修改完成后重新部署你的Web Apps即可生效,上传成功后Toast会在页面顶部居中显示3秒后自动消失,上传失败也会对应展示错误提示。
内容的提问来源于stack exchange,提问作者Tony Jhwueng
相关产品推荐
相关产品推荐

