我正在尝试让 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 Script或Displaying 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/