ruby 我使用POST方法将文件传输到给定的URL,并在Rails中获得错误

juzqafwq  于 2023-06-29  发布在  Ruby
关注(0)|答案(2)|浏览(113)
{
  "body": "Unsupported method.",
  "code": "400",
  "message": "",
  "res": {
    "connection": [
      "close"
    ],
    "content-length": [
      "19"
    ],
    "content-type": [
      "text;charset=ISO-8859-1"
    ],
    "date": [
      "Mon, 20 Sep 2021 05:37:36 GMT"
    ]
  }
}

进入空气制动器时出现上述错误

uri = URI(URL it is constant)
req = Net::HTTP::Post.new(uri)
req.set_form(['upload', File.open("#{file_name}")], 'multipart/form-data')
req.set_form_data("mac" => mac)
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
res = http.request(req)

case res
when Net::HTTPSuccess, Net::HTTPRedirection
  Rails.logger.info "File sent successgully"
  # OK
else
  Airbrake.notify("File transfer failed !", {code: res.code, message: res.message, body: res.body, res: res})
j2cgzkjk

j2cgzkjk1#

这对我很有效

uri = URI.parse(RAKUTEN_URL)
    File.open("#{file_name}") do |transfile|
      Net::HTTP.start(uri.host, uri.port, use_ssl: true) do |http|
        req = Net::HTTP::Post::Multipart.new(
          uri.path,
          mac: encoded_mac,
          file: UploadIO.new(transfile, "multipart/formdata", File.basename("#{file_name}")),
        )
        response = http.request(req)
        case response
        when Net::HTTPSuccess, Net::HTTPRedirection
          #OK
          Rails.logger.info("File sent successfully. Don't panic its only for testing ! #{response}")
        else
          Airbrake.notify("File transfer failed ! #{response}")
        end
      end
    end
6ioyuze2

6ioyuze22#

我们有一个类似的用例,最后使用了Net::HTTP::Post

...
req = Net::HTTP::Post.new(uri.path)
req.set_form(
  [
    ['mac', encoded_mac],
    [
      'file', 
      transfile, 
      { 
        filename: File.basename(file_name), 
        content_type: 'application/json' 
      }
    ]
  ],
  'multipart/form-data'
)
response = http.request(req)
...

相关问题