Sample Script for Resumable Upload to Google Drive using Axios with Node.js

Gists

This is a sample script for the resumable upload using Axios with Node.js.

Sample script

In this sample script, as a sample situation in order to explain the resumable upload, the file data is loaded from the local PC, and the data is uploaded to Google Drive with the resumable upload.

const axios = require("axios");
const fs = require("fs").promises;

async function sample() {
  const filepath = "./###"; // Please set the filename and file path of the upload file.

  const new_access_token = "###"; // Please set your access token.
  const name = "###"; // Please set the filename on Google Drive.
  const mimeType = "###"; // Please set the mimeType of the uploading file. I thought that when this might not be required to be used.

  // 1. Prepare chunks from loaded file data.
  const split = 262144; // This is a sample chunk size.
  const data = await fs.readFile(filepath);
  const fileSize = data.length;
  const array = [...new Int8Array(data)];
  const chunks = [...Array(Math.ceil(array.length / split))].map((_) =>
    Buffer.from(new Int8Array(array.splice(0, split)))
  );

  // 2. Retrieve endpoint for uploading a file.
  const res1 = await axios({
    method: "POST",
    url: "https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable",
    headers: {
      Authorization: `Bearer ${new_access_token}`,
      "Content-Type": "application/json",
    },
    data: JSON.stringify({ name, mimeType }),
  });
  const { location } = res1.headers;

  // 3. Upload the data using chunks.
  let start = 0;
  for (let i = 0; i < chunks.length; i++) {
    const end = start + chunks[i].length - 1;
    const res2 = await axios({
      method: "PUT",
      url: location,
      headers: { "Content-Range": `bytes ${start}-${end}/${fileSize}` },
      data: chunks[i],
    }).catch(({ response }) =>
      console.log({ status: response.status, message: response.data })
    );
    start = end + 1;
    if (res2?.data) console.log(res2?.data);
  }
}

sample();

Testing

When this sample script is run, the following result is obtained.

When the file upload is not finished, the following message is shown.

{ "status": 308, "message": "" }

When the file upload is finished, the following message is shown.

{
  "kind": "drive#file",
  "id": "###",
  "name": "###",
  "mimeType": "###"
}

References

 Share!