在 nodeJS 中导出 google 驱动文件

Export google drive file in nodeJS

我想导出 google 驱动文件,但我以前不知道文件类型。我使用 drive.files.export 但它需要我不知道的 mimeType。来自 drive.files.get 的 mimeType 不能用于导出。如果我只有文件ID,如何下载文件?

根据文件是否为 G Suite 文档,您应遵循的下载过程有所不同。

如果文件是 a G Suite document, you have to use files.export and specify which mimeType you want to export your file to. See here for a reference of the different Google documents and the supported export MIME types. If you want to export your file to different MIME types depending on which type it is in Drive, you can first do files.get,并且根据文件的 mimeType 和引用的 table,将其导出为相应的类型。例如,如果您的文件的 MIME 类型是 application/vnd.google-apps.spreadsheet,您可能希望将其导出为 application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.

如果文件不是 G Suite 文档,您必须使用 files.get to download and set the parameter alt to media, as explained in the official documentation。这是对应于在 Node.js 中执行此操作的代码片段,如那里所指定:

var fileId = 'your-file-id';
var dest = fs.createWriteStream('/tmp/photo.jpg');
drive.files.get({
  fileId: fileId,
  alt: 'media'
})
    .on('end', function () {
      console.log('Done');
    })
    .on('error', function (err) {
      console.log('Error during download', err);
    })
    .pipe(dest);

所以,综上所述,我要做的是,首先,通过 files.get 获取要导出的文件的 mimeType,并基于此 mimeType(取决于文件是否是G Suite 文档和哪种类型的文档),以一种或另一种方式下载文件。

参考:

希望对您有所帮助。