0

I am using the ruby native library to do multipart/form-data API POST call. In this call, I am sending both json and files, but from the server side, the file is not uploaded correctly. Sometimes, it is uploaded successfully.

boundary = '----WebKitFormBoundary7MA4YWxkTrZu0gW'
url = URI("http://localhost:3000/pdfs")

http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
request = Net::HTTP::Post.new(url)

request["authorization"] = "Bearer ddghfgdjh54544fdgdfghj"
request["accept"] = 'application/json'
request["content-type"] = "multipart/form-data; boundary=#{boundary}"
request["cache-control"] = 'no-cache'



body = []
# JSON data
body << "--#{boundary}\r\nContent-Disposition: form-data;"
body << "name=\"profile\"\r\n\r\n"
body << {user: {name:"xyz",email:"xyz@gmail.com"} }.to_json
body <<  "\r\n"

#File data

  body << "--#{boundary}\r\n"
  body << "Content-Disposition: form-data;"
  body << "name=\"profile\"; filename=\"#{username}.pdf\"\r\nContent-Type: application/pdf\r\n"
  body << "#{File.read('/home/pdfs/profile.pdf')}\r\n"


request.body = body.join
response = http.request(request)

1 Answers1

0

I think you should use BASE64 for file upload. The primary use case of base64 encoding is when you want to store or transfer data with a restricted set of characters; i.e. when you can't pass an arbitrary value in each byte. Base64 allows one to encode 8 bit data into 6 bits for transmission on those types of format

Decodes a base 64 encoded string to its original representation.

ActiveSupport::Base64.decode64("T3JpZ2luYWwgdW5lbmNvZGVkIHN0cmluZw==")
# => "Original unencoded string"
Kaushlendra Tomar
  • 1,410
  • 10
  • 16