-3

I have an HTTP API to which I can transfer files as below:

curl -T /my/file/path http://server.name/api/file.in

How can I translate this into Ruby code?

1 Answers1

0

Looks like a duplicate of this question, the accepted answer here will probably help you out: Ruby: How to post a file via HTTP as multipart/form-data?

Using PUT and rest-client

Per the comments below, I realized the curl -T command appears to be doing a HTTP PUT with the data parameter being the binary data from the file. Using the rest-client ruby gem I believe the following code, possibly with minor variation, -should- work for you:

require 'rest-client'

RestClient.put "http://server.name/api/file.in", File.read("/my/file/path")

You may need to set the content-type header for certain types of files, though curl -T didn't appear to be doing that. In that case, you'd do:

RestClient.put "http://server.name/api/file.in", File.read("/my/file/path"), :content_type => 'text/plain'

Source: https://github.com/rest-client/rest-client/blob/master/lib/restclient.rb comments on RestClient module.

Community
  • 1
  • 1
mordocai
  • 83
  • 7
  • I don't think it is a duplicate of that. In my case, there is no attribute to send the file in. This API deals with plain transfer file (-T option in curl). – user3700496 Jun 02 '14 at 18:44
  • Quite correct @user3700496. Sorry about that. Researching this, Curl is doing a PUT with File: in the request. I had always done file uploads using POST. Let me research this a bit and i'll get back to you. – mordocai Jun 02 '14 at 19:07
  • @user3700496 Updated answer, I believe it now accurately answers your question. – mordocai Jun 02 '14 at 19:38
  • Appreciate your help, but it does not work. I don't think -T just dumps the file content in request body as plain text. I really need to replicate exactly what -T does in Ruby. – user3700496 Jun 03 '14 at 01:38
  • @user3700496 I checked using wireshark. Curl -T just dumps the file data into the body of the request. Unless ruby is doing something with the data, or curl does something special with the particular filetype(I noticed it treated jpegs special) it should work. You might try using file.open with "rb" for read binary, but it shouldn't really change anything. In any case the RestClient.put should work, you might just have to tweak the options more. – mordocai Jun 03 '14 at 04:51
  • Yeah, I tried it a bit but couldn't get it work. At last settled to executing it like this from my Ruby code => %x(curl -T /my/file/path http://server.name/api/file.in). Thanks for the help! – user3700496 Jun 03 '14 at 10:02