我正在关注这篇文章,并使我的应用脚本完美运行。来自谷歌驱动器的图片已成功上传到电子表格并进入单元格。
我的脚本运行了大约 3 个月,没有任何问题,然后突然停止运行。出现错误异常:从 URL 地址上传图片时出错或地址无效:“https://lh3.googleusercontent.com/drive-storage/......”
appscript 中是否发生了任何导致脚本停止工作的事情?
这是实际的代码
function myFunction() {
const imageFileId = "fileIDhere"; // Please set the file ID of the image on Google Drive.
// Prepare image.
const url = Drive.Files.get(imageFileId).thumbnailLink.replace(
/\=s.+/,
"=s512"
); // When =s512 is changed to =s1000, the width of the image becomes 1000 pixels.
const image = SpreadsheetApp.newCellImage().setSourceUrl(url).build();
// Put image over cells.
SpreadsheetApp.getActiveSheet().getRange("B2").setValue(image);
}
谢谢你
我也有同样的情况。目前看来,缩略图链接并不是 Drive API 检索到的公共链接。我认为这是由于Google方面的规范发生了变化。那么,现阶段,进行以下修改如何呢?在这种情况下,使用数据 URL 而不是公共链接将图像放入单元格中。
在此修改中,直接使用来自
imageFileId
的图像blob。
function myFunction() {
const imageFileId = "###"; // Please set the file ID of the image on Google Drive.
// Prepare image.
const file = DriveApp.getFileById(imageFileId);
const base64 = Utilities.base64Encode(file.getBlob().getBytes());
const image = SpreadsheetApp.newCellImage().setSourceUrl(`data:${file.getMimeType()};base64,${base64}`).build();
// Put image over cells.
SpreadsheetApp.getActiveSheet().getRange("B2").setValue(image);
}
在此修改中,使用来自
imageFileId
的缩略图链接的图像 blob。如果您的图像尺寸很大,此模式可能很有用。
function myFunction() {
const imageFileId = "###"; // Please set the file ID of the image on Google Drive.
// Prepare image.
const url = `https://drive.google.com/thumbnail?sz=w512&id=${imageFileId}`; // Ref: https://stackoverflow.com/a/31504086
const blob = UrlFetchApp.fetch(url, { headers: { authorization: "Bearer " + ScriptApp.getOAuthToken() } }).getBlob();
const base64 = Utilities.base64Encode(blob.getBytes());
const image = SpreadsheetApp.newCellImage().setSourceUrl(`data:image/png;base64,${base64}`).build();
// Put image over cells.
SpreadsheetApp.getActiveSheet().getRange("B2").setValue(image);
}