javascript - 从 Google Drive 获取基于脚本的网页的图像

标签 javascript google-apps-script

我正在尝试让 google 驱动器中的 png 图像出现在 google apps 脚本 html 页面上。如果图像只是位于网络上某处的 URL(请参阅下面的注释行),但不是来自 google 驱动器,我可以让图像显示在脚本 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 页面上缺少图像,缺少图像的网址以 script.googleusercontent.com/Blob 结尾

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

感谢任何帮助。

最佳答案

如果您可以看到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%">

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

希望这有帮助。

关于javascript - 从 Google Drive 获取基于脚本的网页的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40197318/

相关文章:

javascript - 在使用它之前,我是否必须在 Javascript 中的对象内部声明一个空数组?

javascript - 带动画的 Google map SVG 标记

google-apps-script - 使用 Google App 脚本创建 Google 日历提醒

javascript - 使用 Google Spreadsheet 作为 JSON 文件,使用桌面到数据表会返回错误

date - 如何在 Google 脚本中创建特定日期

javascript - 在 Google Apps 脚本中调用函数

javascript - jQuery/CSS 动画 - 在 FF 中暂停和 Chrome 跳回并开始是不正确的

javascript - AngularJS 不清理由 ng-include 创建的子作用域

javascript - 如何防止 Javascript 禁用按钮在回发后重新启用?

google-apps-script - 使用 Google Slides Apps 脚本设置表格的宽度和高度