首页 > 解决方案 > 我正在使用 POST 方法将文件传输到给定的 URL,并在 rails 中出现错误

问题描述

{
  "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"
    ]
  }
}

以上错误进入Airbrake

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})

标签: ruby-on-railsrubyhttps

解决方案


这对我有用

  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

推荐阅读