Ruby - Twitter Gem -使用INIT, APPEND和FINALIZE命令上传图像



我正在尝试使用Twitter gem和Twitter REST API上传一个简单的图像到Twitter。我总是得到以下错误Twitter::Error::BadRequest: Segments do not add up to provided total file size.

如果我是对的,我明白在过程结束时(FINALIZE),我上传的图像的大小(在APPEND期间)与我在第一次(在INIT期间)声明的大小不同。

下面是我的代码:
file_path = "/Users/folder/image.png"
filesize = File.open(file_path).size
init_request = Twitter::REST::Request.new(TWITTER, :post, "https://upload.twitter.com/1.1/media/upload.json?command=INIT&total_bytes=#{filesize}&media_type=image/png").perform
media_id = init_request[:media_id]
Twitter::REST::Request.new(TWITTER, :post, "https://upload.twitter.com/1.1/media/upload.json?command=APPEND&media_id=#{media_id}&media=#{file_path}.png&segment_index=0").perform
Twitter::REST::Request.new(TWITTER, :post, "https://upload.twitter.com/1.1/media/upload.json?command=FINALIZE&media_id=#{media_id}").perform

提示吗?谢谢!

看一下gem的repo中的例子。

如果你想上传一篇文章,它可以像这样简单:

client.update_with_media("I'm tweeting with @gem!", File.new("/Users/folder/image.png"))`

如果你只是想上传并获得media_id的引用,这应该工作:

client.upload(File.new("/Users/folder/image.png"))

这个请求是错误的:

Twitter::REST::Request.new(TWITTER, :post, "https://upload.twitter.com/1.1/media/upload.json?command=APPEND&media_id=#{media_id}&media=#{file_path}.png&segment_index=0").perform

因为您没有将媒体文件作为多部分数据上传,您只将文件路径作为文本发送。因此,您应该像这样使用Twitter::REST::Request:

Twitter::REST::Request.new(TWITTER,
                           :post, "https://upload.twitter.com/1.1/media/upload.json",
                           command: 'APPEND',
                           media_id: media_id,
                           media: File.open(file_path),
                           segment_index: 0).perform

最新更新