ruby-on-rails - 带有自定义标头的 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.start
request.set_form form_data, body['file'].content_type
invalid enctype: image/jpeg
正确发送标题的一件事是替换它:
form_data = body.to_a
request.set_form form_data, 'multipart/form-data'
和
request.body = body.to_json
但这不会像我使用的外部 API 所期望的那样发送文件。
你对我如何解决这个问题有什么建议吗?谢谢!
解决方案
推荐阅读
- javascript - 如何使用 JavaScript 将 mySQL 查询到 HTML 页面?
- javascript - 如何使用 post 方法在两个跨度之间添加代码?
- security - 最好(和正确)使用 nmap 扫描自己的计算机?
- python - 如何在 django 中运行 html 和 jquery 代码?
- r - 识别 TRUE 和 FALSE 序列中最后一个 TRUE 的位置
- canvas - HTML5 画布填充文本的原点
- flutter - 如何获取文本的宽度和高度?
- android - 如何在没有商户账户的情况下使用 Braintree 进行买卖双方的付款?
- javascript - ReactJS - 如何正确呈现源自父组件并传递给子组件的内容?
- javascript - 反应组件模块“classProperties”当前未启用