Rails:多部分/表单数据的 ActionDispatch::Request.parameter_parsers [英] Rails: ActionDispatch::Request.parameter_parsers for multipart/form-data

查看:39
本文介绍了Rails:多部分/表单数据的 ActionDispatch::Request.parameter_parsers的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的 rails API 中,我添加了一个初始化程序,它将 JSON 输入的键从蛇形大小写更改为下划线分隔.像这样:

In my rails API, I have added an initialiser that will change the keys of the JSON input from snake-case to underscore-separated. Like so:

ActionDispatch::Request.parameter_parsers[:json] = -> (raw_post) {
    data = ActiveSupport::JSON.decode(raw_post)
    data = {:_json => data} unless data.is_a?(Hash)

    data.deep_transform_keys!(&:underscore)
}

现在,某些 API 将与标头一起传递:content-type: multipart/form-data 而不是 application/json

Now, certain APIs will be passed with the header: content-type: multipart/form-data instead of application/json

我想对这些 API 做同样的事情.那就是添加一个初始化器来转换参数中键的大小写.

I want to do the same for such APIs. That is add an initialiser that will convert the case of the keys in the parameters.

我尝试了 ActionDispatch::Request.parameter_parsers[:form_data] 但它不起作用.

I tried ActionDispatch::Request.parameter_parsers[:form_data] but it dit not work.

我怎样才能做到这一点?

How can I achieve this?

推荐答案

当你看DEFAULT_PARSERS,它使用 Mime 类,所以无论我们最终使用什么都可能需要可以通过 Mime 类识别.所以我们可以检查

When you look at the DEFAULT_PARSERS, it uses the Mime class, so whatever we end up using will likely need to be recognizable by the Mime class. So we can check Mime::Types to see what's available.

在那个页面上,我们看到 content-type: multipart/form-data 被映射到 :multipart_form.确实,同时使用

On that page, we see that content-type: multipart/form-data is mapped to :multipart_form. Indeed, while using

ActionDispatch::Request.parameter_parsers[:multipart_form] = -> (raw_post) {
  raise "Parsing Parameters: #{raw_post}"
}

然后提交带有文件字段的表单,我可以触发错误.

and then submitting a form with a file field, I can trigger the error.

这篇关于Rails:多部分/表单数据的 ActionDispatch::Request.parameter_parsers的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆