javascriptgoogle-apps-script

How to insert image to google forms using apps script?


I have a google forms with image upload. I captured onSubmit event value and process it to make a new google sheets. I have difficulties in inserting the image that is stored on google drive to the newly created sheet. My current script to insert the image looks like this:

    function insertImage(sheet) {

  const urlRaw = sheet.getRange('C42').getValue();
  if (!urlRaw) {
    console.log('No URL provided in cell C42.');
    return;
  }

  // Extract the file ID from the URL
  let fileId;
  if (urlRaw.includes("open?id=")) {
    fileId = urlRaw.split("open?id=")[1].split("&")[0];
  } else if (urlRaw.includes("/d/")) {
    fileId = urlRaw.split("/d/")[1].split("/")[0];
  } else {
    console.error("Invalid Google Drive URL format.");
    return;
  }

  const imgRange = sheet.getRange('C42')
  const imgUrl = DriveApp.getFileById(fileId).getUrl()
  sheet.insertImage(imgUrl,imgRange.getColumn(), imgRange.getRow())

}

Solution

  • Use .getBlob() to Insert Images from Google Drive into Google Sheets

    Instead of using .getUrl, I used .getBlob to get the image as a Blob, which directly handled the image data. I also removed the imgUrl and passed the Blob directly to insertImage.

    I changed this part of your code:

    const imgRange = sheet.getRange('C42')
          sheet.insertImage(DriveApp.getFileById(fileId).getBlob(), imgRange.getColumn(), imgRange.getRow())
    

    Complete Code:

    function insertImage() {
      var ss = SpreadsheetApp.getActiveSpreadsheet();
      var sheet = ss.getActiveSheet();
      const urlRaw = sheet.getRange('C42').getValue();
      if (!urlRaw) {
        console.log('No URL provided in cell C42.');
        return;
      }
    
      let fileId;
      if (urlRaw.includes("open?id=")) {
        fileId = urlRaw.split("open?id=")[1].split("&")[0];
      } else if (urlRaw.includes("/d/")) {
        fileId = urlRaw.split("/d/")[1].split("/")[0];
      } else {
        console.error("Invalid Google Drive URL format.");
        return;
      }
      const imgRange = sheet.getRange('C42')
      sheet.insertImage(DriveApp.getFileById(fileId).getBlob(), imgRange.getColumn(), imgRange.getRow())
    }
    

    Note: The file size of the image may also cause an error.

    Sample Output:

    Sample

    Reference:

    getBlob()