Skip to content

Instantly share code, notes, and snippets.

@tanaikech
Created December 7, 2020 01:47
Show Gist options
  • Save tanaikech/426345c24e46da3ac7268f31b76bb3e4 to your computer and use it in GitHub Desktop.
Save tanaikech/426345c24e46da3ac7268f31b76bb3e4 to your computer and use it in GitHub Desktop.
Uploading Image Files to Google Photos using axios

Uploading Image Files to Google Photos using axios

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment