简体   繁体   中英

Cant post media to twitter api using nodejs

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,/, "");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM