问题描述
所以我有一个网站,用户可以在其中上传图像文件(我一直在使用 113KB PNG 文件进行测试).点击提交按钮后,图像数据被编码为 base64,然后以 POST 请求正文中的 JSON 格式发送到托管在 heroku 上的 node.js 服务器.然后服务器获取图像数据并解析 JSON.然后,我使用节点模块 twitter
从 heroku 服务器向 media/upload
端点发出 POST 请求.我尝试使用它来发布有效的常规状态,因此这不是身份验证问题.在 twitter
模块文档的示例中,他们这样做(原始二进制文件,而不是 base64):
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) { ... }
但是,按照我的做法,我实际上无法读取文件——我所拥有的只是来自 JSON 字符串的编码数据.无论如何,这就是我所拥有的:
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)
}
});
我怀疑问题是因为我传入的是数据而不是 readFileSync
的结果.关于如何在不使用它的情况下做到这一点的任何想法?
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?
推荐答案
发布 base64 编码的图片时,请务必在邮件的图片部分设置Content-Transfer-Encoding: base64".
API 文档不是最好的.示例中有 media_type
但要确定:
The API docs aren't the best. There's a media_type
in the examples but to be sure:
client.post
在 twitter.js 使用params
调用 __request
是否不设置标题
__request
client.post
in twitter.js calls__request
with theparams
__request
does not set a the header
如果您将 post
调用中的参数从 {media_data: data}
更改为 {media: data}
是否有效?如果没有,似乎设置标题的唯一方法是打开 PR 或尝试在初始化客户端时将它们提供为默认值:Twitter(options)
.此处已经设置了一些标题.
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.
仅供参考 - 我已经为您打开了一个 GitHub 问题.加入对话!https://github.com/desmondmorris/node-twitter/issues/292
FYI - I've opened a GitHub issue for you. Join the conversation! https://github.com/desmondmorris/node-twitter/issues/292
这篇关于Twitter API:媒体/上传 400 错误请求:媒体类型无法识别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!