在 Node.JS 中从 google 驱动器下载 public 图像

Download public images from google drive in Node.JS

我在 google 驱动器上有一组图像,并且每个图像都有一个 link 列表。他们可能是也可能不是 public(任何拥有 link 的人)。我想将它们保存在本地并单独嵌入到网页中,因为将它们直接嵌入到img标签中会导致图像加载延迟。

我需要通过 Node.JS 脚本以编程方式下载它们。 Node.JS 脚本是我构建管道的一部分,因此我不能完全使用 gdown(python 包)。

我尝试了 google 驱动器 API,但 OAuth 令牌每小时都会过期,而且我的构建每周都在 cron 作业上进行,并提交到存储库。

我有哪些选择?

这里有一个例子

[
  {
    "name": "A",
    "photoUrl": "https://drive.google.com/uc?export=view&id=1km3V6PP70MTUsNWFEgdVea6jv-0BMnRT"
  },
  {
    "name": "B",
    "photoUrl": "https://drive.google.com/uc?export=view&id=1km3V6PP70MTUsNWFEgdVea6jv-0BMnRT"
  },
]

我相信你的现状和你的目标如下。

  • 所有文件中一个文件的最大文件大小为 3 MB。

  • 您要下载文件,当文件公开共享时,作为二进制数据使用Node.js。

    • 在这种情况下,您可以使用 request 模块。
  • 您想将数据用于其他进程。

  • 您的列表如下。而且,您想使用 ${name}.jpg 这样的文件名。由此可见,所有文件都是JPEG文件。

      [
        {
          "name": "A",
          "photoUrl": "https://drive.google.com/uc?export=view&id=1km3V6PP70MTUsNWFEgdVea6jv-0BMnRT"
        },
        {
          "name": "B",
          "photoUrl": "https://drive.google.com/uc?export=view&id=1km3V6PP70MTUsNWFEgdVea6jv-0BMnRT"
        },
      ]
    

在这种情况下,下面的示例脚本怎么样?

示例脚本:

const fs = require("fs");
const request = require("request");

async function main() {
  const download = ({ name, url }) =>
    new Promise((resolve, reject) => {
      request({ url: url, encoding: null }, (err, res, buf) => {
        if (err) {
          reject(err);
          return;
        }
        if (res.headers["content-type"].includes("text/html")) {
          console.log(`This file (${url}) is not publicly shared.`);
          resolve(null);
          return;
        }

        // When you use the following script, you can save the downloaded image data as the file.
        fs.writeFile(
          name,
          buf,
          {
            flag: "a",
          },
          (err) => {
            if (err) reject(err);
          }
        );

        resolve(buf);
      });
    });

  // This is a sample list from your question.
  const list = [
    {
      name: "A",
      photoUrl:
        "https://drive.google.com/uc?export=view&id=1km3V6PP70MTUsNWFEgdVea6jv-0BMnRT",
    },
    {
      name: "B",
      photoUrl:
        "https://drive.google.com/uc?export=view&id=1km3V6PP70MTUsNWFEgdVea6jv-0BMnRT",
    },
  ];

  // 1. Create filename and convert the URL for downloading.
  const reqs = list.map(({ name, photoUrl }) => ({
    name: `${name}.jpg`,
    url: `https://drive.google.com/uc?export=download&id=${
      photoUrl.split("=")[2]
    }`,
  }));
  
  // 2. Download the files.
  const buffers = await Promise.all(reqs.map((obj) => download(obj)));
  console.log(buffers);
}

main();
  • 您的网址已转换为 webContentLink。这样,当文件大小很小如 3 MB 时,可以使用 webContentLink.
  • 下载文件
  • 在此示例脚本中,公开共享文件时,将下载并保存文件。而且,您可以将下载的数据用作缓冲区。在这种情况下,当文件未公开共享时,返回 null
  • 在你的情况下,文件列表中的所有文件都是JPEG图像。使用这个,通过检查响应头的内容类型,当不包含text/html时,可以认为该文件没有公开共享。

注意:

  • 如果要下载大文件,建议使用API键下载。这样,您的脚本就可以简单地修改。当不能使用API密钥时,可以使用.
  • 的过程下载