Ok so I have an express server that I am using to post a picture to twitter using media/upload
.
app.post('/api/post-picture', (req, res) =>{
client.post('media/upload', {"media": data}, // Here lies the problem
function(error, media, response) {
if (!error) {
client.post('statuses/update', {
status: 'TEST PICTURE',
media_ids: media.media_id_string
}, function(error, tweet, response){
if(!error){
res.json({status: 'success'})
}else{
res.json({error: response})
}
})
}else{
res.json({error: response})
}
});
});
In my req.body.media
I have a base64 encoded string that i am sending to my express server. I then take the base64 encoded image and I convert it back to raw binary data with:"
var buf = Buffer.from(req.body.media, 'base64');
And then I pass in that buf
variable to
client.post('media/upload', {"media": buf},
For some weird reason twitters api says it cant recongize that media type: Exact error message:
"body": "{\"request\":\"\\/1.1\\/media\\/upload.json\",\"error\":\"media type unrecognized.\"}"
Their api says: "Media should be The raw binary file content being uploaded"
What am I doing wrong here?
https://developer.twitter.com/en/docs/media/upload-media/api-reference/post-media-upload.html
Working code snippet:
app.post('/api/post-picture', (req, res) =>{
// var encodedimage = Buffer.from(data).toString('base64')
var buf = Buffer.from(req.body.media.toString(), 'base64');
client.post('media/upload', {"media": buf},
function(error, media, response) {
if (!error) {
client.post('statuses/update', {
status: 'TEST PICTURE',
media_ids: media.media_id_string
}, function(error, tweet, response){
if(!error){
res.json({status: 'success'})
}else{
res.json({error: response})
}
})
}else{
res.json({error: response})
}
});
});
Twitters api also accepts a base64 encoded string but I also provide that and it also errors out on me.
data:image/jpeg;base64
needs to be removed from the data in order for twitter to accept it, which is not documented anywhere on their api.
You can do this with
var base64Data = encodedImage.replace(/^data:image\/jpg;base64,/, "");