Google脚本上传图片至Drive生成Sheet链接提交按钮失效修复求助
修复Google Sheet上传图片脚本无响应问题
问题说明
运行addImage()弹出上传对话框后,点击提交按钮无响应,无法完成图片上传及链接生成操作。
原脚本核心问题
- Blob创建参数错误:前端传递的数据结构与后端
Utilities.newBlob的参数要求不匹配,导致无法生成有效文件对象; - 行号逻辑不合理:固定传递行号
2,未关联当前活动单元格的实际行号; - 数据传递结构混乱:前端传递的数组参数在后端解析时容易出错,缺乏结构化处理。
修复后的完整代码
Code.gs
function addImage() { // 获取当前活动单元格的行号 var activeRow = SpreadsheetApp.getActiveRange().getRow(); var htmlTemp = HtmlService.createTemplateFromFile('Index'); // 将活动行号传递给前端页面 htmlTemp.rowNum = activeRow; var html = htmlTemp.evaluate().setHeight(96).setWidth(415); SpreadsheetApp.getUi().showModalDialog(html, '上传图片'); } function upload(fileData) { // 解构前端传递的结构化数据 const { bytes, type, name, rowNum } = fileData; // 正确创建文件Blob对象 const blob = Utilities.newBlob(bytes, type, name); // 替换为你的Google Drive文件夹ID const targetFolder = DriveApp.getFolderById('[你的文件夹ID]'); const uploadedFile = targetFolder.createFile(blob); // 获取文件链接并写入指定单元格 const fileUrl = uploadedFile.getUrl(); const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1'); const urlCell = sheet.getRange(rowNum, 5); urlCell.setFormula(`=HYPERLINK("${fileUrl}", "查看图片")`); return "上传完成"; }
Index.html
<!DOCTYPE html> <html> <head> <base target="_center"> <link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons1.css"> </head> <body> <form id="myForm"> 请选择要上传的图片<br><br> <input type="hidden" name="rowNum" id="rowNum" value="<?= rowNum ?>"/> <input type="file" name="file" id="file" accept="image/*" /> <input type="button" value="提交" class="action" onclick="handleUpload(this.parentNode)" /> <input type="button" value="关闭" onclick="google.script.host.close()" /> </form> <script> // 阻止表单默认提交行为 document.getElementById('myForm').addEventListener('submit', e => e.preventDefault()); function handleUpload(form) { const file = form.file.files[0]; if (!file) { alert('请先选择一个图片文件'); return; } const reader = new FileReader(); reader.readAsArrayBuffer(file); reader.onload = function(e) { // 构造结构化数据传递给后端 const fileData = { bytes: [...new Int8Array(e.target.result)], type: file.type, name: file.name, rowNum: form.rowNum.value }; // 调用后端上传函数,添加成功/失败处理 google.script.run .withSuccessHandler(msg => { console.log(msg); google.script.host.close(); }) .withFailureHandler(err => { alert('上传失败: ' + err.message); }) .upload(fileData); }; } </script> </body> </html>
关键修复点
- 动态关联行号:从当前活动单元格获取行号,确保链接生成在正确位置;
- 结构化数据传递:用对象替代数组传递文件信息,避免参数顺序错误;
- 完善错误处理:增加文件选择校验和上传失败提示,提升用户体验;
- 简化冗余依赖:移除未使用的jQuery库,减少资源加载;
- Blob参数修正:按照
Utilities.newBlob的要求传递参数,确保文件能正常生成。
注意:需将
Code.gs中的[你的文件夹ID]替换为实际的Google Drive文件夹ID,并确保脚本已获取Drive的读写权限。
内容的提问来源于stack exchange,提问作者weizer
相关产品推荐
相关产品推荐

