问题
So I've got a website where a user uploads an image file (I've been testing with a 113KB PNG file). After hitting the submit button, the image data gets encoded into base64 and then is sent to a node.js server hosted on heroku in a JSON in the body of the POST request. The server then takes the image data and parses the JSON. Then, I make a POST from the heroku server to the media/upload
endpoint using the node module, twitter
. I've tried using it to post a regular status which worked, so it's not an authentication problem. In the example on the twitter
module's documentation, they do this (raw binary, not base64):
var data = require('fs').readFileSync('image.jpg');
client.post('media/upload', {media: data}, function(error, media, response) { ... }
However, the way I'm doing it, I can't actually read a file -- all I've got is the encoded data from the JSON string. Anyway, here's what I've got:
...
let data = JSON.parse(req.rawBody).imageb64;
//console.log(data);
client.post('media/upload', {media_data: data}, function(error, media, response) {
if (!error) {
console.log(media);
var status = {
status: 'api test',
media_ids: media.media_id_string
}
client.post('statuses/update', status, function(error, tweet, response) {
if (!error) {
console.log(tweet);
}
});
} else {
console.log(response)
}
});
I suspect the problem is because I'm passing in the data rather than the result of readFileSync
. Any ideas on how I can do this without using it?
回答1:
There's a little note in the fine print of the docs that may help:
When posting base64 encoded images, be sure to set the “Content-Transfer-Encoding: base64” on the image part of the message.
The API docs aren't the best. There's a media_type
in the examples but to be sure:
client.post
in twitter.js calls__request
with theparams
- __request does not set a the header
Does it work if you change the params in your call to post
from {media_data: data}
to {media: data}
? If not, it seems like the only way to set the headers would be either open a PR or to try providing them as the default when you initialize the client: Twitter(options)
. There are already some headers set here.
FYI - I've opened a GitHub issue for you. Join the conversation! https://github.com/desmondmorris/node-twitter/issues/292
来源:https://stackoverflow.com/questions/50261958/twitter-api-media-upload-400-bad-request-media-type-unrecognized