Reputation: 475
I can't figure out how to use the gapi.client.youtube.thumbnails.set
client-side JavaScript? All the examples I've found are for node.js and use the following syntax:
gapi.client.youtube.thumbnails.set({
videoId: 'xxxx',
media: {
mimeType: "image/jpeg",
body: fs.createReadStream("some-file.jpg"),
}
})
Obviously the fs.createReadStream
isn't available in client-side JavaScript. How can I use that API with an image that the user loads via an <input file="type">
element? I've tried everything I could think of as the value of the body
media key:
fileInputNode
fileInputNode.files
fileInputNode.files[0]
fileInputNode.files[0].arrayBuffer
fileInputNode.files[0].arrayBuffer()
fileInputNode.files[0].stream
fileInputNode.files[0].stream()
where fileInputNode
is the HTML element for the file input. In all cases the call to gapi.client.youtube.thumbnails.set
does not send any data in the request body, and only sets the videoId
query parameter. So not surprisingly the request fails with "The request does not include the image content."
Does anybody know how to use this method?
Upvotes: 1
Views: 64
Reputation: 925
You can give a try with readAsArrayBuffer
from FileReader
. Here is a demo:
const fileInput = document.getElementById('my-input');
function readFileData(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = (event) => resolve(event.target.result);
reader.onerror = (error) => reject(error);
reader.readAsArrayBuffer(file);
});
}
//Event listener for file input
fileInput.addEventListener('change', async (event) => {
const file = event.target.files[0];
if (!file) {
return;
}
const fileData = await readFileData(file);
// Call the YouTube API
try {
const response = await gapi.client.youtube.thumbnails.set({
videoId: 'xxxx'
media: {
mimeType: file.type,
body: fileData,
},
});
console.log(response);
} catch (error) {
console.error('Error:', error);
}
});
Upvotes: 0