简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM