javascript - 如何从谷歌驱动器下载动态文件

标签 javascript node.js express google-drive-api

菜鸟问题,我刚刚开始使用 Google Drive API v3。当我只有 fileId 时,如何从谷歌驱动器下载动态文件。文件可以是图片、pdf 或文档。

我尝试搜索但找不到与此相关的任何引用或示例。

这是我目前所拥有的,但它只下载特定的文件扩展名。

downloadFile(req, res) {
    const auth = new google.auth.JWT(
       client_email,
       null,
       private_key,
      SCOPES,
    );
    const { fileId } = req.params;
    const drive = google.drive({ version: 'v3', auth});
    var dest = fs.createWriteStream('./tmp/downloads/dummy.pdf')
    
    drive.files.get({
      fileId,
      alt: 'media',
    }, { 
      responseType: 'stream' 
    }).then((driveResponse) => {
      driveResponse.data.on('end', () => {
       console.log(`downloading fileID ${fileId}`);
      })
      .on('error', (err) => {
       console.log(err);
      })
      .on('data', (d) => {
        console.log(d);
      })
      .pipe(dest)
    })
    .catch((err) => {
      console.log(err);
    })
  }

有没有办法从谷歌驱动器下载动态文件?

最佳答案

我相信你的目标如下。

  • 您想使用服务帐户和文件 ID 从 Google 云端硬盘下载文件。
  • 文件包括 Google Docs 文件和除 Google Docs 文件之外的文件。
  • 您想使用适用于 Node.js 的 googleapis 实现这一目标。

修改点:

  • 不幸的是,从它只下载特定的文件扩展名。,我无法了解您的详细情况。但我猜你的问题的原因可能是由于同时下载了 Google 文档文件和除 Google 文档文件之外的文件。
  • 下载Google Docs文件时,需要使用Drive API中的“Files: export”方法下载文件。
  • 下载除Google Docs文件以外的文件时,需要使用Drive API中的“Files: get”方法下载文件。
  • 我认为上述情况可能是您遇到问题的原因。
  • 为了同时下载 Google Docs 文件和 Google Docs 文件以外的文件,我建议采用以下流程。
    1. 检查文件 ID 的 mimeType。
    2. 通过 mimeType 使用每种方法下载文件。

当以上几点反射(reflect)到你的脚本中时,它变成如下。

修改后的脚本:

来自:

var dest = fs.createWriteStream('./tmp/downloads/dummy.pdf')

drive.files.get({
  fileId,
  alt: 'media',
}, { 
  responseType: 'stream' 
}).then((driveResponse) => {
  driveResponse.data.on('end', () => {
   console.log(`downloading fileID ${fileId}`);
  })
  .on('error', (err) => {
   console.log(err);
  })
  .on('data', (d) => {
    console.log(d);
  })
  .pipe(dest)
})
.catch((err) => {
  console.log(err);
})

收件人:

drive.files.get({ fileId, fields: "*" }, async (err, { data }) => {
  if (err) {
    console.log(err);
    return;
  }
  let filename = data.name;
  const mimeType = data.mimeType;
  let res;
  if (mimeType.includes("application/vnd.google-apps")) {
    const convertMimeTypes = {
      "application/vnd.google-apps.document": {
        type:
          "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
        ext: ".docx",
      },
      "application/vnd.google-apps.spreadsheet": {
        type:
          "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
        ext: ".xlsx",
      },
      "application/vnd.google-apps.presentation": {
        type:
          "application/vnd.openxmlformats-officedocument.presentationml.presentation",
        ext: ".pptx",
      },
    };
    filename += convertMimeTypes[mimeType].ext;
    res = await drive.files.export(
      {
        fileId,
        mimeType: convertMimeTypes[mimeType].type,
      },
      { responseType: "stream" }
    );
  } else {
    res = await drive.files.get(
      {
        fileId,
        alt: "media",
      },
      { responseType: "stream" }
    );
  }
  const dest = fs.createWriteStream(filename);
  res.data
    .on("end", () => console.log("Done."))
    .on("error", (err) => {
      console.log(err);
      return process.exit();
    })
    .pipe(dest);
});

注意事项:

  • 在此修改中,我在 convertMimeTypes 准备了 3 种类型的 Google Docs 文件。当您要下载其他mimeTypes时,请修改convertMimeTypes。例如,在这种情况下,Google Docs 文件将下载为 Microsoft Docs 文件。

引用资料:

关于javascript - 如何从谷歌驱动器下载动态文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64337805/

相关文章:

javascript - React Native类型错误: undefined is not an object (evaluating '_ref.item' )

javascript - 存在隐藏元素时 jQuery 可排序滞后

javascript - meteor .js 错误 : Exception from sub xGHk6PkFTQ9uv8ncg TypeError: Cannot call method 'find' of undefined

JavaScript 正则表达式 : successive matches

node.js - 使用 Nodejs 和 Monk 进行 Mongodb 身份验证

node.js - node.js、express 和 EJS 的 WebStorm 代码补全

javascript - 如何在具有多个匹配项的 JavaScript RegEx 中仅返回捕获的组

javascript - 在按钮上使用 'this' 的 jQuery 选择

javascript - 我遇到 'req.param.id' 问题

javascript - 样式切换器帮助