Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invalid request parameters: invalid %-encoding when upload file to Rails api only server

I am working on web app that use Reactjs as a front-end and Rails5 api only app as a back-end

This is the data that i send to the server as Request payload

------WebKitFormBoundaryCD1o71UpVNpU4v86
Content-Disposition: form-data; name="user[username]"

oeuoeoaeaoe
------WebKitFormBoundaryCD1o71UpVNpU4v86
Content-Disposition: form-data; name="user[profile_image]"; filename="gggg.jpg"
Content-Type: image/jpeg


------WebKitFormBoundaryCD1o71UpVNpU4v86--

This is my controller

def update_with_image
    user = current_user
    if user.update_attributes(user_update_params)
      # Handle a successful update.
      render json: user, status: 200
    else
      render json: { errors: user.errors }, status: 422
    end
  end


  private

  def user_update_params
    params.require(:user).permit(:username,:profile_image)
  end

So when i tried to upload image to Rails server i got this error

ActionController::BadRequest (Invalid request parameters: invalid %-encoding ("user[username]"

oeuoeoaeaoe
------WebKitFormBoundaryCD1o71UpVNpU4v86
Content-Disposition: form-data; name="user[profile_image]"; filename="gggg.jpg"
Content-Type: image/jpeg

????JFIF????@6"??

??F!1AQ "aq?
#2???B?????$3Rb?%Cr??????       ??A!1A"Qaq?2???BR???#b??3rS?$Cs????
                                                                   ??%)):

rack (2.0.1) lib/rack/query_parser.rb:72:in `rescue in parse_nested_query'
rack (2.0.1) lib/rack/query_parser.rb:61:in `parse_nested_query'

** I use Rack::Cors and Rack::Attack as my middileware

How can i fix this?

Thanks!

like image 767
Varis Darasirikul Avatar asked Nov 18 '16 20:11

Varis Darasirikul


1 Answers

Wasted one day on this problem.

A correct answer is here: https://stackoverflow.com/a/60812593/11792577

Don't set Content-Type header when you use fetch to post multipart/form-data to Rails api server.

WRONG

// this is not working
fetch(
  url,
  {
    method: 'POST', // or 'PUT'
    headers: {
       'Content-Type': 'multipart/form-data'
    },
    /*
    * or
    * headers: {
    *   'Content-Type': '',
    *   'Content-Type': undefined,
    *   'Content-Type': null,
    * },
    */
    body
  }
);

CORRECT

fetch(url, {
   method: 'POST',
   headers: {},
   body
});

// or delete headers['Content-Type'] if necessary
like image 131
glinda93 Avatar answered Nov 15 '22 17:11

glinda93