Axios

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.

Simple Script of Resumable Upload with Google Drive API for Axios

Gists

This is a simple sample script for achieving the resumable upload to Google Drive using Axios. In order to achieve the resumable upload, at first, it is required to retrieve the location, which is the endpoint of upload. The location is included in the response headers. After the location was retrieved, the file can be uploaded to the location URL.

In this sample, a text data is uploaded with the resumable upload using a single chunk.

Uploading Image Files to Google Photos using axios

Gists

This is a sample script for uploading the image files to the specific album in Google Photos using axios.

Before you use this script, please retrieve the access token for uploading the files using Google Photos API.

Sample script

In this sample script, several image files can be uploaded.

<input type="file" id="files" name="file" multiple />
<input type="button" onclick="main()" value="upload" />

<script>
  function upload({ files, albumId, accessToken }) {
    const description = new Date().toISOString();
    const promises = Array.from(files).map((file) => {
      return new Promise((r) => {
        axios
          .post("https://photoslibrary.googleapis.com/v1/uploads", file, {
            headers: {
              "Content-Type": "application/octet-stream",
              "X-Goog-Upload-File-Name": file.name,
              "X-Goog-Upload-Protocol": "raw",
              Authorization: `Bearer ${accessToken}`,
            },
          })
          .then(({ data }) => {
            r({
              description: description,
              simpleMediaItem: { fileName: file.name, uploadToken: data },
            });
          });
      });
    });
    return Promise.all(promises).then((e) => {
      return new Promise((resolve, reject) => {
        console.log(e);
        axios
          .post(
            "https://photoslibrary.googleapis.com/v1/mediaItems:batchCreate",
            JSON.stringify({ albumId: albumId, newMediaItems: e }),
            {
              headers: {
                "Content-type": "application/json",
                Authorization: `Bearer ${accessToken}`,
              },
            }
          )
          .then(resolve)
          .catch(reject);
      });
    });
  }

  // This function is run.
  function main() {
    const obj = {
      files: document.getElementById("files").files,
      albumId: "###", // Please set the album ID.
      accessToken: "###", // Please set your access token.
    };
    upload(obj)
      .then((e) => console.log(e))
      .catch((err) => console.log(err));
  }
</script>

References