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.
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>
- Google Photos APIs
- Upload media
- Method: mediaItems.batchCreate
- Related question in Stackoverflow.