MultiPart File Upload in Ruby using Knack API

Viewed 204

Having difficulty uploading a file using the Knack API with a Ruby script. The KNACK API documentation states:

Uploading a file or image via the Knack API is a two step process. The first will perform an HTTP POST request with a multipart/form-data content type to the following URL: https://api.knack.com/v1/applications/app_id/assets/file/upload.

curl -X POST "https://api.knack.com/v1/applications/YOUR-APP-ID/assets/file/upload" \
  -H 'content-type: multipart/form-data' \
  -H 'x-knack-rest-api-key: YOUR-API-KEY' \
  -F "files=@/path/to/your/file.txt"

I have tried the following in Ruby and receive a 400 bad request response code.

def multipart_form_post  

  uri = URI.parse "https://api.knack.com/v1/applications/xxxxxxx/assets/file/upload" 

  file_path = "c:/temp/test.txt"

  newline = "\r\n"
  filename = File.basename(file_path)

  boundary = "----WebKitFormBoundary#{Time.now.nsec}"


  post_body = []
  post_body << "--#{boundary}#{newline}"
  post_body << "Content-Disposition: form-data; name=\"File\"; filename=\"#{filename}\"#{newline}"
  post_body << "Content-Type: application/octet-stream#{newline}"
  post_body << "#{newline}"
  post_body << File.read(file_path)
  post_body << "#{newline}--#{boundary}--#{newline}"



  http = Net::HTTP.new uri.host, uri.port
  http.use_ssl = true
  http.verify_mode = OpenSSL::SSL::VERIFY_NONE

  request = Net::HTTP::Post.new uri.request_uri
  request.body = post_body.join
  request["Content-Type"] = "multipart/form-data, boundary=#{boundary}"
  request["x-knack-rest-api-key"]     = "xxxxxx"
  request['cache-control'] = "no-cache"


  response = http.request request
  puts "#{response.code} #{response.message}"
  return response

end

Any help is appreciated.

1 Answers

I finally located my issue. The issue was a comma instead of a semi-colon between "multipart/form-data; boundary=#{boundary}".

Related