-
Hey everyone. I'm quite new to Buffers and readable streams, and am quite confused on how to work with them. I currently want to be able to generate a dynamic Image using Say, I have a base64 string, and I send it over to an API route in Next.js. What exactly should my next step be? I've tried to use the data: {
request: '/1.1/media/upload.json',
error: 'media type unrecognized.'
} Code snippet generating the image const element = printRef.current // ref points to a componenet
const canvas = await html2canvas(element, {
useCORS: true,
windowHeight: 900,
windowWidth: 1600,
})
const data = canvas.toDataURL('image/jpeg')
setSec2(data) The function which sends over the data to the API route looks like: async function tweetImage() {
const res = await fetch('/api/twitter/tw', {
method: 'POST',
headers: {
'Content-type': 'application/json',
},
body: JSON.stringify({
name: sec2, // base64 string generated using html2canvas
}),
})
const data = await res.json()
} The server-side code looks like: try {
console.log('name', name) // name is buffer
const buffer = Buffer.from(name)
/*Converted Buffer data looks like:
<Buffer 64 61 74 61 3a 69 6d 61 67 65 2f 6a 70 65 67 3b 62 61 73 65 36 34 2c 2f 39 6a 2f 34 41 41 51 53 6b 5a 4a 52 67 41
42 41 51 41 41 41 51 41 42 41 41 44 ... 19441 more bytes>
*/
const uploadImage = await v1.uploadMedia(buffer, {
mimeType: EUploadMimeType.Jpeg,
})
const tweet = await v1.tweet(
'Test tweet with Image',
{
media_ids: uploadImage,
}
)
return res.status(200).json({
works: true,
uploadedImage: uploadImage.media_id_string,
allDetails: uploadImage,
})
} This has been eating my head a lot. Any help would be appreciated, thanks! :) |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
Hey everyone. I figured out the issue. I was encoding the base64 string incorrectly. Previously: const buff = Buffer.from(name,'base64') Now: const buff = Buffer.from(name.replace(/^data:image\/\w+;base64,/, ""),'base64') Refer this for more information! Hope this helps. |
Beta Was this translation helpful? Give feedback.
Hey everyone. I figured out the issue. I was encoding the base64 string incorrectly.
Previously:
Now:
Refer this for more information!
Hope this helps.