Google Photos API

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

GAS Library - GPhotoApp

Overview

This is a GAS library for retrieving and creating the albums and media items using Google Photo API using Google Apps Script (GAS).

Description

In the current stage, Google Photo API is not included in Advanced Google services. But in order to use Google Photo API with Google Apps Script, I created this as a GAS library. So in the current stage, in order to use this library, the following flow is required.