【问题标题】:MultiPart File Upload in Ruby using Knack API使用 Knack API 在 Ruby 中上传多部分文件
【发布时间】:2023-03-19 00:36:01
【问题描述】:

使用带有 Ruby 脚本的 Knack API 上传文件时遇到困难。 KNACK API 文档指出:

通过 Knack API 上传文件或图像是一个两步过程。第一个将对以下 URL 执行具有 multipart/form-data 内容类型的 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

感谢任何帮助。

【问题讨论】:

    标签: ruby


    【解决方案1】:

    我终于找到了我的问题。问题是“multipart/form-data;boundary=#{boundary}”之间的逗号而不是分号。

    【讨论】:

      猜你喜欢
      • 2010-10-31
      • 1970-01-01
      • 2016-04-23
      • 2015-08-01
      • 2018-08-06
      • 2021-01-19
      • 2013-03-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多