2016-09-30 25 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