简体   繁体   中英

Insert Image by URL Doesn't Work in Google Apps Script

One of the responses in a Google Forms that I created is uploading an image, which gets saved in my Google Drive along with the URL in the linked spreadsheet. In Google slides I have created an Apps Script and successfully able to create slides for each row/entry along with text from that row, from the spreadsheet, but are having difficulty trying to insert an image using by URL. At run time I get the exception thrown "The image at URL... could not be retrieved. Please make sure the image is valid and publicly accessible." I also get the same error when I manually try to insert the image by URL via the menu bar. All folders and files in my drive are not restricted, so any one on the internet can view the image with this link. And I have tested that out both in my browser and others and it successfully opens the image, but not in Slides. I must be missing something, but can't figure it out.

Here is some code I am using from the function, but not including the reference to the spreadsheet. Have tried adding '/edit', '/view' to the end of the URL as well, but with same results. Logger does shows the URL is being grabbed from the sheet.

function CreateSlides() {
  var deck = SlidesApp.getActivePresentation();
  var a = 2;  // data begins in second row in spreadsheet
  while (sheet.getRange(a,2,1,1).getValue() != "") {
  //Insert new slide if not first slide
    if (a != 2) {
      slide = deck.insertSlide(a-2,SlidesApp.PredefinedLayout.BLANK);  //add new slide
    } else {
      slide = deck.getSlides()[0]; //get first slide
    }
  // Insert image of painting
  Logger.log(sheet.getRange(paintingURLCol + a).getValue());
  var picture = slide.insertImage(sheet.getRange(paintingURLCol + a).getValue() + '/view');
  // Edit picture size and position
  // Increment counter to next row in sheet
  a++;
  }
}

The URLs logged by Google Form by upload question type can't be used with methods like insertImage(URL) because those URLs aren't supported. Instead you should use:

https://drive.google.com/uc?id=DRIVE_FILE_ID

The above becase the URLs logged to the spreadsheet points to a page with the image embedded not to the actual image file.

Related

Thanks Rubén. And that's what I actually did and it solved the issue. Here is the sample code that I used for the solution.

var fileURL = sheet.getRange(paintingURLCol + a).getValue();
var fileID = fileURL.substr(fileURL.search("=")+1);  //strip off text before id= in the URL
var file = DriveApp.getFileById(fileID);
slide.insertImage(file);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM