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

前端 未结 2 1158
梦如初夏
梦如初夏 2021-01-22 21:21

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::Reques         


        
相关标签:
2条回答
  • 2021-01-22 21:25

    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.

    0 讨论(0)
  • 2021-01-22 21:28

    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
    
    0 讨论(0)
提交回复
热议问题