rubynet-http

Is there a way to set Content-type in multipart request with set_form method?


I need to set Content-type = "application/pdf" to a parameter of a request with the method "set_form" from net/http class but it always shows me Content-Type = "application/octet-stream".

I already checked out the documentation for set_form but I don't know how to properly set the Content-Type.

    http = Net::HTTP.new(uri.host, uri.port)
    request = Net::HTTP::Post.new("#{path}")
    request.set_form([
        ["parameter1","#{parameter1}"],
        ["parameter2","#{parameter2}"],
        ["attachment", File.new("/home/name.pdf", "rb")]
    ], 'multipart/form-data')
    response = http.request(request)

I have tried this code to set opt hash like documentation but I have received the same response:

uri = URI.parse("#{host}")
    http = Net::HTTP.new(uri.host, uri.port)
    request = Net::HTTP::Post.new("#{path}")
    request.set_form([
        ["parameter1","#{parameter1}"],
        ["parameter2","#{parameter2}"],
        ["attachment", File.new("/home/name.pdf", "rb"), { "Content-Type" => "application/pdf" }]
    ], 'multipart/form-data')
    response = http.request(request)

The actual output is still Content-Type: application/octet-stream but I need:

... Content-Disposition: form-data; name=\"attachment\"; filename=\"name.pdf\"\r\nContent-Type: application/pdf\r\n\r\n%PDF-1.5\r%\xE2\xE ...

Solution

  • For those who are still looking for how to do it with Net::HTTP, you should be doing:

    request.set_form(
      [
        ['attachment', File.open('myfile.pdf'), content_type: 'application/pdf', filename: 'my-better-filename.pdf']
      ],
      'multipart/form-data'
    )
    

    Options content_type and filename are optional. By default, content type is application/octet-stream and filename is the name of the file you are opening.