使用带有Ruby脚本的Knack API上载文件有困难。 KNACK API文档指出:
通过Knack API上载文件或图像是一个两步过程。第一个将对以下URL执行具有多部分/表单数据内容类型的HTTP POST请求: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"
我在Ruby中尝试了以下操作,并收到400错误的请求响应代码。
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
感谢您的帮助。
答案 0 :(得分:0)
我终于找到了问题所在。问题是“ multipart / form-data; boundary =#{boundary}”之间的逗号而不是分号。