Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
334 views
in Technique[技术] by (71.8m points)

javascript - How to download dynamic files from google drive

noob question, I'm just getting started with Google Drive API v3. How can I download dynamic file from google drive when I only have fileId. file can be, image, pdf, or docs.

I tried searching but I couldn't found any reference or example related to this.

This what I have so far but it only download specific file extension.

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);
    })
  }

Is there way to download dynamic files from google drive?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I believe your goal as follows.

  • You want to download the files from Google Drive using the service account and the file ID.
  • The files include both Google Docs files and the files except for Google Docs files.
  • You want to achieve this using googleapis for Node.js.

Modification points:

  • Unfortunately, from it only download specific file extension., I cannot understand about the detail of your situation. But I guess that the reason of your issue might be due to downloading both Google Docs files and the files except for Google Docs files.
  • When Google Docs files are downloaded, the files are required to be downloaded using the method of "Files: export" in Drive API.
  • When the files except for Google Docs files are downloaded, the files are required to be downloaded using the method of "Files: get" in Drive API.
  • I thought that above situation might be the reason of your issue.
  • In order to download both Google Docs files and the files except for Google Docs files, I propose the following flow.
    1. Check the mimeType of the file ID.
    2. Download the file using each method by the mimeType.

When above points are reflected to your script, it becomes as follows.

Modified script:

From:

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);
})

To:

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);
});

Note:

  • In this modification, I prepared 3 types of Google Docs files at convertMimeTypes. When you want to download other mimeTypes, please modify convertMimeTypes. In this case, for example, Google Docs files are downloaded as Microsoft Docs files.

References:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...