问题
I am working on an express node app that posts to twitter when a user inputs an image into a form. I am saving the image locally before uploading, which works. After I encode the file to base64, I try to upload the base64-encoded file to Twitter using twit's media/upload feature. When I do this, I get an error saying "media type unrecognized."
Here is my code:
app.post('/tweet', function(req, res){
var time = new Date().getTime()
let image = req.files.image
var imgpath = './images/img' + time + '.jpg'
image.mv(imgpath, function(err) {
if (err){
return res.status(500).send(err);
}
});
var b64content = fs.readFileSync(imgpath, { encoding: 'base64' })
T.post('media/upload', {media: b64content}, function(err, data, res) {
if (err) console.log(err);
console.log(data);
T.post('statuses/update', {status: 'posted picture at: ' + time, media_ids: [data.media_id_string]}, function(err, params, res) {
if (err) console.log(err);
console.log(params);
});
});
return res.redirect('/')
})
Thank you!
回答1:
Got it!. I needed to put the T.post
code in the brackets of image.mv
's function
回答2:
use postMediaChunked
function
var filePath = '/absolute/path/to/file.png'
T.postMediaChunked({ file_path: filePath }, function (err, data, response) {
console.log(data)
})
来源:https://stackoverflow.com/questions/49019575/media-type-unrecognized-when-uploading-an-image-to-twitter-using-npm-twit