使用 Drive api 获取驱动器文件的 blob

Aps*_*anj 2 blob google-apps-script google-drive-api

abc.dat我使用下面的脚本来获取通过我的 Apps 脚本项目生成的文件blob 。有了 Drive 服务,这一切就变得很简单。使用的 oauthScope 是https://www.googleapis.com/auth/drive.readonly

function ReadData() {
  var files;

  var folders = DriveApp.getFoldersByName("Holder");
  if (folders.hasNext()) {
    var folder = folders.next();
    var files = folder.getFiles();

    while (files.hasNext()){
      file = files.next();
        if(file.getName()=='abc.dat'){
          var content = file.getBlob().getDataAsString();
          return content;
        }    
    }
  }
  return '';
}
Run Code Online (Sandbox Code Playgroud)

为了减少身份验证范围,现在我正在修改代码以完全删除oauthScopehttps://www.googleapis.com/auth/drive.readonly并仅使用https://www.googleapis.com/auth/drive.fileoauthScope。

使用 Drive api,我没有找到获取文件 blob 的直接方法。我使用下面的脚本来获取 Word 文档文件的 blob。但它不适用于 .dat 文件并出现错误fileNotExportable, Export only supports Docs Editors files, code 403

function getBlob(fileID, format){

  var url = "https://www.googleapis.com/drive/v3/files/" + fileID + "/export?mimeType="+ format;

  var blob = UrlFetchApp.fetch(url, {
    method: "get",
    headers: {"Authorization": "Bearer " + ScriptApp.getOAuthToken()},
    muteHttpExceptions: true
  }).getBlob();

  return blob;
}
Run Code Online (Sandbox Code Playgroud)

找到这篇文章并尝试更改中的exportwith 。返回现在显示“未找到”。geturlblob.getDataAsString()

我在创建 abc.dat 文件时使用的 mimeType 是application/octet-stream .dat。但是当检查生成的文件时,它的mimeType是text/plain. 所以我使用“text/plain”作为函数中“format”参数的输入getBlob

.dat 文件创建代码:

 var connectionsFile = {
      title: filename,
      mimetype: "application/octet-stream .dat",
      parents: [{'id':folder.getId()}],
    };
      var blobData = Utilities.newBlob(contents);
      file = Drive.Files.insert(connectionsFile,blobData);
  }
Run Code Online (Sandbox Code Playgroud)

如何修改此代码以从文件中获取 blob?或者还有其他办法吗?

提前致谢!

Tan*_*ike 5

我认为,在你的情况下,需要使用get方法而不是export方法。因为export该方法用于 Google 文档文件(文档、电子表格、幻灯片等)。当你的脚本修改后,下面的修改怎么样?

修改后的脚本:

function getBlob(fileID) {
  var url = "https://www.googleapis.com/drive/v3/files/" + fileID + "?alt=media";
  var blob = UrlFetchApp.fetch(url, {
    method: "get",
    headers: { "Authorization": "Bearer " + ScriptApp.getOAuthToken() },
    muteHttpExceptions: true
  }).getBlob();
  return blob;
}
Run Code Online (Sandbox Code Playgroud)

参考: