【问题标题】:Google Apps Scripts - How to replace a file?Google Apps 脚本 - 如何替换文件?
【发布时间】:2013-11-12 10:25:30
【问题描述】:

我正在尝试使用脚本替换 Google Drive 文件夹中的 PDF 文件。由于 GAS 没有提供添加修订(版本)的方法,我试图替换文件的内容,但我得到的只是一个空白 PDF。

我无法使用 DriveApp.File 类,因为我们的管理员已禁用新 API,因此我必须改用 DocsList.File。

  • 输入:
    • OldFile.pdf(8 页)
    • NewFile.pdf(20 页)
  • 预期输出:
    • OldFile.pdf 与 NewFile.pdf 内容相同
  • 实际输出:
    • OldFile.pdf 包含 20 个空白页。

流程:

var old = DocsList.getFileById("####");
var new = DocsList.getFileById("####");
old.replace(new.getContentAsString());

有什么想法吗? 提前非常感谢。

PS.:我也试过先调用 old.clear(),但我想说问题出在 getContentAsString 方法上。

【问题讨论】:

  • getContentAsString() 闻起来像是根据某些字符编码进行一些解码,例如UTF-8,这将有效地破坏一些 PDF 内容,例如页面内容流通常被压缩,因此对变化非常敏感。
  • 您是否需要保留与要求相同的文档 ID?如果没有,您可以简单地删除并重命名...
  • 是的,我需要相同的 ID,因为它是从网络链接的。
  • 您可以使用stackoverflow.com/a/24226885/1058108 的解决方案。基本上,您使用 Drive.Files.update(file, fileId, updatedBlob) API,如果您通过 Resources > Advanced Google Services > Drive API > ON 激活它就可以使用它

标签: file pdf google-apps-script google-drive-api


【解决方案1】:

Advanced Drive Service 可用于替换 Google Drive 中现有 PDF 文件的内容。此答案还包括一个如何更新共享云端硬盘中的 PDF 文件的示例。

function overwriteFile(blobOfNewContent,currentFileID) {
  var currentFile;
  
  currentFile = DriveApp.getFileById(currentFileID);    
  
  if (currentFile) {//If there is a truthy value for the current file
    Drive.Files.update({
      title: currentFile.getName(), mimeType: currentFile.getMimeType()
    }, currentFile.getId(), blobOfNewContent);
  }
}

参考文献

使用共享云端硬盘的示例:

Drive.Files.update({ title: currentFile.getName(), mimeType: 
  currentFile.getMimeType() }, currentFile.getId(), blobOfNewContent, 
  {supportsTeamDrives: true});

【讨论】:

  • 在团队驱动的情况下,您的电话将类似于Drive.Files.update({ title: currentFile.getName(), mimeType: currentFile.getMimeType() }, currentFile.getId(), blobOfNewContent,{supportsTeamDrives: true});
【解决方案2】:

尝试将其作为 blob 数据类型。

【讨论】:

  • 我也试过了,但结果是一样的。 old.replace(new.getBlob().getDataAsString());它产生相同的结果,一个不可读的 pdf。
  • 不要将其转换为字符串。有一些方法可以从 blob 创建文件。
  • 我知道。我可以从 blob 创建一个文件,而且效果很好。我的问题是我需要覆盖文件的内容,以保留其 ID。
  • 那么它不可能从本机应用程序脚本 api 中做你想做的事情。您需要使用驱动器 API(已为您阻止)上传文件的新修订版,而且您必须弄清楚之前如何编辑该修订版(而不是使用 getDataAsString :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-04
  • 1970-01-01
相关资源
最近更新 更多