You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Google Drive指定文件夹图片上传及Google Sheet显示问题求助

问题排查与修复:图片上传至Drive并在Google Sheet显示

核心需求

点击表单按钮「फारम बुझाउनुहोस्」(提交表单)后,将上传图片存入Drive根目录下的「CS_Display_photo-Initial_Request」文件夹,再通过=IMAGE()公式在指定Google Sheet的F1单元格显示图片。

已发现的错误点

  • 前后端字段不匹配:前端发送的formData字段为base64/type/name/sheetName,但后端GAS代码错误使用fileData/mimeType/fileName读取,导致解析失败。
  • 缺少请求头:前端fetch未设置Content-Type: application/json,可能导致GAS无法正确解析JSON请求体。
  • 未引入jQuery依赖:前端使用$('#user_photo')但未加载jQuery库,导致图片预览功能失效。
  • 文件夹与权限问题:若目标文件夹不存在,getFoldersByName().next()直接报错;上传图片默认仅脚本运行者可见,Sheet无法加载私有图片。
  • 未处理Sheet不存在异常:指定工作表名称错误时,代码直接抛出错误。

修复后的完整代码

1. HTML表单代码(含预览与请求修复)

<form id="photo_form"> 
    <fieldset> 
        <legend>फोटो विवरण</legend> 
        <label for="user_photo">हालसालै खिचिएको फोटो</label>  
        हालसालै खिचिएको पासफोटो वा आफ्नो फोटो आफै खिचेको खण्डमा उज्यलो प्रकासमा दुइवटा कान आएको  प्रष्ट फोटो अपलोड गर्नुहोला ।  
        <input type="file" name="userPhoto" id="user_photo" accept="image/*"> 
        <div id="form_show_photo"> </div> 
    </fieldset> 
    <input type="hidden" name="sheetName" value="Photo Form"> 
    <button type="submit" id="myButton">फारम बुझाउनुहोस्   </button> 
</form> 
<div id="message" style="display:none;"></div> 

<!-- 引入jQuery库,修复预览功能 -->
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>    
    document.addEventListener("DOMContentLoaded", () => {
        const url = "https://script.google.com/macros/s/AKfycbxdFUvsssd_0bAoKmI0ZrUlaQfkI6E73ypmN8r6j_5vrVWBcJ0u_zVJQyBTJ7E-7R6B_w/exec";
        const form = document.querySelector("form");
        const fileInput = document.querySelector("input[type='file']");

        // 图片预览功能
        $('#user_photo').change(function () {
            const file = this.files[0];
            const url = URL.createObjectURL(file);
            $('#form_show_photo').html(`<img src="${url}" style="max-width:200px;">`);
        });

        form.addEventListener("submit", (event) => {
            event.preventDefault();
            if (!fileInput.files.length) {
                alert("请选择图片后提交");
                return;
            }

            const fr = new FileReader();
            fr.addEventListener("loadend", () => {
                const spt = fr.result.split("base64,")[1];
                // 包含sheetName字段
                const formData = {
                    base64: spt,
                    type: fileInput.files[0].type,
                    name: fileInput.files[0].name,
                    sheetName: document.querySelector("input[name='sheetName']").value
                };

                fetch(url, {
                    method: "POST",
                    headers: {
                        "Content-Type": "application/json" // 添加请求头
                    },
                    body: JSON.stringify(formData),
                })
                .then((response) => response.text())
                .then((data) => {
                    console.log(data);
                    $('#message').text(data).show();
                })
                .catch((error) => {
                    console.error("请求错误:", error);
                    $('#message').text(`错误: ${error.message}`).show();
                });
            });

            fr.readAsDataURL(fileInput.files[0]);
        });
    });
</script>

2. Google Apps Script代码(含错误处理与权限设置)

function doPost(e) { 
    try { 
        const formData = JSON.parse(e.postData.contents); 
        const folderName = "CS_Display_photo-Initial_Request"; 
        
        // 查找或创建目标文件夹(避免文件夹不存在报错)
        let parentFolder;
        const folders = DriveApp.getFoldersByName(folderName);
        if (folders.hasNext()) {
            parentFolder = folders.next();
        } else {
            parentFolder = DriveApp.createFolder(folderName);
        }

        // 解码base64数据并创建文件
        const data = Utilities.base64Decode(formData.base64);
        const blob = Utilities.newBlob(data, formData.type, formData.name);
        const file = parentFolder.createFile(blob);
        
        // 设置文件权限为"知道链接的人可查看",确保Sheet能加载图片
        file.setSharing(DriveApp.Access.ANYONE_WITH_LINK, DriveApp.Permission.VIEW);
        
        const fileId = file.getId();

        // 更新Google Sheet
        const spreadsheetId = "130wSROY1_mscyXvuftCTbENkpqxVcmEsVKhWRa4WFwo"; 
        const sheetName = formData.sheetName; 
        const spreadsheet = SpreadsheetApp.openById(spreadsheetId);
        const sheet = spreadsheet.getSheetByName(sheetName);
        
        if (!sheet) {
            return ContentService.createTextOutput(`错误: 未找到工作表 ${sheetName}`);
        }

        // 设置IMAGE公式
        const imageUrl = `https://drive.google.com/uc?id=${fileId}`;
        const imageFormula = `=IMAGE("${imageUrl}", 4, 50, 100)`;
        const cell = sheet.getRange("F1"); 
        cell.setFormula(imageFormula);

        return ContentService.createTextOutput("文件上传成功,图片已添加至工作表。");

    } catch (err) {
        return ContentService.createTextOutput(`错误: ${err.message}`);
    }
}

验证步骤

  1. 脚本部署权限:将Google Apps脚本部署时的「谁可以访问应用」设置为「任何人,甚至匿名」,否则前端请求会被拒绝。
  2. 文件夹检查:确认Drive根目录下存在「CS_Display_photo-Initial_Request」文件夹,若不存在,脚本会自动创建。
  3. 测试上传:选择图片提交表单,查看Drive文件夹是否新增图片,检查Sheet的F1单元格是否成功加载图片。

内容的提问来源于stack exchange,提问作者Ningsang Jabegu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 21:37:52