Rails: ActionDispatch::Request.parameter_parsers for multipart/form-data

℡╲_俬逩灬. 提交于 2019-12-02 08:08:45

问题


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

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

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.

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

How can I achieve this?


回答1:


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.

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.




回答2:


Although, according to Simple Lime's answer, :multipart_form is the right key for the default parser for requests with content-type: multipart/form-data, it does not work like the way it does for JSON.

This is the work around I implemented:

class ApplicationController < ActionController::API
    before_action :transform_params_if_multipart!

    private 
    def transform_params_if_multipart!
        params.deep_transform_keys!(&:underscore) if /^multipart\/form-data*/.match(request.headers['content-type'])
    end
end


来源:https://stackoverflow.com/questions/45096629/rails-actiondispatchrequest-parameter-parsers-for-multipart-form-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!