2016-04-13 18 views
0

我試圖發送Paperclip上傳的圖像到API。如何使用Net :: HTTP發送PNG圖像

如何對它進行編碼?

現在我正在使用attachment.queued_for_write[:original].read來獲取該PNG的實際文件內容,並嘗試將其發送到我的請求正文中。但服務器沒有它。

當我通過郵遞員發送請求時,它工作正常。郵差是如何編碼的?不幸的是,試圖從Postman生成Ruby代碼不起作用,它只是在請求的主體中顯示文件[Object object]

+0

這取決於第三方API期待您的文件。查看API的文檔。 [最小,完整和可驗證示例](http://stackoverflow.com/help/mcve) – Uzbekjon

+0

啓動Wireshark。比較Postman的POST請求和Net :: HTTP的POST請求。 [這個答案](http://stackoverflow.com/a/30827339/5006469)可能會幫助你。 – rdupz

+0

@Uzbekjon我的問題是,郵差是如何編碼的?這是一個rinky dink API,其創建者不知道問題的答案。但它適用於郵差,因此我的問題。 – bevanb

回答

1

Postman docs say它使用標準表單發佈。 A quick search導致了此代碼:

require "net/http" 
require "uri" 

# Token used to terminate the file in the post body. Make sure it is not 
# present in the file you're uploading. 
# You might want to use `SecureRandom` class to generate this random strings 
BOUNDARY = "AaB03x" 

uri = URI.parse("http://something.com/uploads") 
file = "/path/to/your/testfile.txt" 

post_body = [] 
post_body < < "--#{BOUNDARY}\r\n" 
post_body < < "Content-Disposition: form-data; name='datafile'; filename='#{File.basename(file)}'\r\n" 
post_body < < "Content-Type: text/plain\r\n" 
post_body < < "\r\n" 
post_body < < File.read(file) 
post_body < < "\r\n--#{BOUNDARY}--\r\n" 

http = Net::HTTP.new(uri.host, uri.port) 
request = Net::HTTP::Post.new(uri.request_uri) 
request.body = post_body.join 
request["Content-Type"] = "multipart/form-data, boundary=#{BOUNDARY}" 

http.request(request) 
+0

下面是一個更詳細的解決方案:https://coderwall.com/p/c-mu-a/http-posts-in-ruby – bevanb