【问题标题】:Get Image From Google Drive for Script-Based Web Page从 Google Drive 获取基于脚本的网页的图像
【发布时间】:2016-10-23 16:06:30
【问题描述】:

我正在尝试在 google 驱动器中获取 png 图像以显示在 google 应用程序脚本 html 页面上。如果图像只是在网络上某处的 URL 上,我可以让图像出现在脚本 html 页面上(见下面注释掉的行),但不是来自谷歌驱动器。这是我试图将其作为 blob 获取然后在图像标签中使用的代码的一部分:

function getImage() {
//The next 2 lines don't produce the image on the page
  var image = DriveApp.getFileById('File Id Goes Here').getBlob().getAs('image/png');
  var image = '<img src = "' + image + '" width = "90%">'
  //Note, the next line uncommented produces an image on the page
//var image = '<img src = "https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png" width = "90%">'
return image
}

function doGet() {
  var htmlToAppend = getImage(); 
   var html = HtmlService.createTemplateFromFile('index').evaluate()
              .setTitle('Google Image').append(htmlToAppend).setSandboxMode(HtmlService.SandboxMode.IFRAME);  
  return html;    
}

结果是脚本生成的 html 页面上缺少图片,缺少图片的 URL 以 script.googleusercontent.com/Blob 结尾

关于 Blob 的信息在这里:https://developers.google.com/apps-script/reference/base/blob(在单独的页面/选项卡中打开)

感谢任何帮助。

【问题讨论】:

    标签: javascript google-apps-script


    【解决方案1】:

    如果您可以看到Using base64-encoded images with HtmlService in Apps ScriptDisplaying files (e.g. images) stored in Google Drive on a website,则有一些解决方法可以从驱动器中获取图像。

    一种解决方法是使用IFRAME sandbox mode,但这不支持旧浏览器。

    只需在您的模板上调用 setSandboxMode(),您的数据 URI 应该会按预期工作:

    var output = HtmlService.createHtmlOutput(
    '<img src="data:' + contentType + ';base64,' + encoded + '"/>'
    );
    
    output.setSandboxMode(HtmlService.SandboxMode.IFRAME);
    

    第二个是使用文件的永久链接:

    https://drive.google.com/uc?export=view&id={fileId}
    

    但请注意,Serving images in an Apps Script through HtmlService 已弃用。

    <img src="https://googledrive.com/host/0B12wKjuEcjeiySkhPUTBsbW5j387M/my_image.png" height="95%" width="95%">
    

    另外,避免使用相同的变量名以避免发生错误

    希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-06
      相关资源
      最近更新 更多