首页 > 解决方案 > 带有自定义标头的 Rails Net::HTTP 表单数据

问题描述

我正在尝试通过 form_data 发送文件并将Content-Type标题设置为文件的内容类型(image/png,image/jpeg等)而不是multipart/form-data.

我尝试了多种方法,但这是我的方法:

def fetch(url, body, headers, limit, use_ssl, use_file_content_type)
  raise HTTPRedirectLevelTooDeep, 'HTTP redirect too deep' if limit.zero?

  headers[:'Content-Type'] = body['file'].content_type if use_file_content_type

  uri = URI(url)
  request = Net::HTTP::Post.new(url)

  headers.each { |key, value| request[key.to_s] = value }

  form_data = body.to_a
  request.set_form form_data, 'multipart/form-data'
  
  response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: use_ssl) do |http|
    http.request(request)
  end

  case response
  when Net::HTTPSuccess     then response
  when Net::HTTPRedirection then fetch(response['location'], body, headers, limit - 1)
  else
    response.error!
  end
end

这就像我想要的那样发送正文,但没有正确设置 Content Type 标头(它使用multipart/form-data)。我还尝试在设置表单数据后设置标题: request['Content-Type'] = body['file'].content_type就在之前,http.request(request)但它发送Content-Type: application/x-www-form-urlencoded.

我还尝试在方法中设置标题,或者在方法内部Net::HTTP::Post.new移动所有内容,但它仍然对我不起作用。我也尝试过使用,但这只是说request = Net::HTTP.startrequest.set_form form_data, body['file'].content_typeinvalid enctype: image/jpeg

正确发送标题的一件事是替换它:

form_data = body.to_a
request.set_form form_data, 'multipart/form-data'

request.body = body.to_json

但这不会像我使用的外部 API 所期望的那样发送文件。

你对我如何解决这个问题有什么建议吗?谢谢!

标签: ruby-on-railsrubymultipartform-datacontent-typenet-http

解决方案


推荐阅读