In Ruby, how to send multiple files in single request using RESTClient

48 Views Asked by At

I've been have a issue where I tried to use the RestClient lib to send two or more files to Kotlin Service endpoint where this controller needs to receive a files attributes that is a List<MultipartFile>.

I'm using rest-client (2.0.2), rails (7.0.4.2) and ruby 3.1.2p20

I already try send this requests, but a receive a bad request and in the kotlin service says:

"Required request part 'files' is not present"

 request = @http_client_class.new(
          method: :post,
          url: path,
          payload: { multipart: true, files: files },
          headers: build_header(headers)
        )

I tried this way but the hash in ruby just accept one key per hash, so it just send the second file. And yes I already try to use compare_by_identity method doesn't work

request = @http_client_class.new(
  method: :post,
  url: path,
  payload: {
    :multipart => true,
    :files => files[0],
    :files => files[1]
  },
  headers: build_header(headers)
)

I already tried this but I also receive a bad request and in the kotlin service says "Required request part 'files' is not present"

payload = {
  file1: File.new(file1_path, 'rb'),
  file2: File.new(file2_path, 'rb')
}

And other alternatives that chatgpt, phind and Stack Overflow gave to me.

The curious is when I send one file it works. Request like this

 request = @http_client_class.new(
          method: :post,
          url: path,
          payload: { multipart: true, files: files[0] },
          headers: build_header(headers)
        )

It looks when I have a list the lib RestClient use Utils.flatten_params they change my attributes name from files to files[].

RESOLUTION

I resolved change the lib

Using Net::HTTP::Post::Multipart works.

0

There are 0 best solutions below