2016-09-30 83 views
0

我试图使用Twitter gem和Twitter REST API将简单图像上传到Twitter。我总是得到以下错误Twitter::Error::BadRequest: Segments do not add up to provided total file size.Ruby-Twitter Gem - 使用INIT,APPEND和FINALIZE命令上传图像

如果我是正确的,我知道在该过程(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 

任何提示?谢谢!

+0

没有人给我一只手? :) – Eric

回答

1

看看宝石回购中的examples

如果你想与后上传,也可以是简单的:

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")) 
+0

谢谢!然而,update_with_media被弃用,这就是为什么我这样试图.. – Eric

+0

哦..对不起。我从未使用过这种宝石。你有没有尝试过使用第二种方法,然后'client.update(“Tweet text”,:media_ids => #the_id_from_the_last_call)'? –

+0

@Eric能正常工作吗? –

0

这个请求是错误的:

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