Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Twitter image upload error : media parameter is missing

In the new twitter media upload api said

First, use POST multipart/form-data or base64 encoded files to https://upload.twitter.com/1.1/media/upload.json.

but get error : code 38 "media parameter is missing."

here is my code

var Twitter = require('./twitter.js');
var request = require('request');
var fs = require('fs');
var path = require('path');
var FormData = require('form-data');
var utf8 = require('utf8');
var base64_encode = require('base64').encode;

var oauth = {
    consumer_key: '',
    consumer_secret: '',
    token: '',
    token_secret: ''
};

var form = new FormData();
fs.readFile(__dirname + '/image.jpg', function(err, data) {
    if (err) {
        throw err;
    }
    var encoded = base64_encode(data);
    form.append('media[]', encoded); // I've also tried media instead of media[]
    form.getLength(function(err, length) {
        var r = request.post({
            url: 'https://upload.twitter.com/1.1/media/upload.json',
            oauth: oauth,
        }, function(error, response, body) {
            if (error) {
                console.error(error);
                return;
            }
            console.dir(body);
        });
        r._form = form;
        r.setHeader('content-length', length);
    });
});

I reuse code from this topic : Upload images to twitter API from node.js

Any suggestion? Thank you

like image 872
Methuz Kaewsai-kao Avatar asked Mar 18 '23 05:03

Methuz Kaewsai-kao


1 Answers

Here is what I use to upload media :
(I only use OAuth to create Oauth authentification)
I also add /statuses/update.json to link a new post to your media.

var oauth = require('oauth');
var fs = require('fs');

var a = new oauth.OAuth("https://twitter.com/oauth/request_token",
    "https://twitter.com/oauth/access_token",
    config.consumerKey,
    config.consumerSecret,
    "1.0",
    config.callbackUrl,
    "HMAC-SHA1");

a.post("https://upload.twitter.com/1.1/media/upload.json", oauth_access_token, oauth_access_token_secret, {media:fs.readFileSync(file_path).toString("base64")} ,"" , function (e, data, res){
    if (e) {
        console.error(e);
    }else {
        try{
            data = JSON.parse(data);
        }catch (e){
            console.error("Error Json : " + e);
        }
        console.log(data.media_id);

        a.post("https://api.twitter.com/1.1/statuses/update.json", oauth_access_token, oauth_access_token_secret, {status:message,media_ids:[data.media_id_string]}, "", function (e, data, res){
            if (e) {
                console.error(e);
            }else {
                console.log("Success");
            }
        });
    }
});

Have Fun

like image 124
Neige Avatar answered Mar 26 '23 02:03

Neige