Google Photos API Tutorial to Upload Multiple Photos From Local Storage & HTML5 Form in Browser Using Axios & Javascript Full Project For Beginners

 

 

index.html

 

 

<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>

 

 

In the above script you need to replace the albumId and accessToken from the google developer console

 

Leave a Reply