letsbondiway
letsbondiway

Reputation: 541

How to convert a cURL multipart/form-data POST request to ruby request using rest-client?

I have to implement the curl POST request listed below in Ruby using Rest-Client so that I can upload a file to my server.

curl -X POST --header 'Content-Type: multipart/form-data' --header 'Accept: application/json' --header 'Authorization: Basic jhdsjhdshjhdshdhh' --header 'tenant-code:djdjhhsdsjhjsd=' {"type":"formData"} 'https://myserver.com/blobs/upload?fileName=some.ipa&groupId=098'

I have tried the following -

require 'rest-client'
require 'json'

payload = {
    :multipart => true,
    :file => File.new(path_to_file, 'rb')
}

response = RestClient.post("https://myserver.com/blobs/upload?fileName=some.ipa&groupId=098", payload, {accept: :json, 'tenant-code':"djdjhhsdsjhjsd=", 'Authorization': "Basic jhdsjhdshjhdshdhh"})

This works okay as I get 200 response from the server. However, when I check for the uploaded file on my server it is corrupted.

Is this the right way to do multipart/form-data request using ruby?

I see there is the following in cURL request which is not accounted for in ruby request anywhere.

{"type":"formData"}

Do I need to do something extra for that?

Upvotes: 1

Views: 1034

Answers (1)

letsbondiway
letsbondiway

Reputation: 541

I solved it for my specific case (where I needed to upload an IPA file to my enterprise app store) by changing the request to the following :-

require 'rest-client'
require 'json'

response = RestClient::Request.execute(
  :url => "https://myserver.com/blobs/upload?fileName=some.ipa&groupId=098",
  :method => :post,
  :headers => {
    'Authorization' => "Basic jhdsjhdshjhdshdhh",
    'tenant-code' => "djdjhhsdsjhjsd=",
    'Accept' => 'application/json',
    'Content-Type' => 'application/octet-stream',
    'Expect' => '100-continue'
  },
  :payload => File.open(path_to_file, "rb")
)

Basically, the content type needed to be octet-stream and Expect header needs to be set too.

Hopefully, it helps someone who comes looking for something like this.

Upvotes: 1

Related Questions