13

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!

5
  • Check your post Headers 'Content-Type' Commented Nov 28, 2016 at 8:17
  • 1
    I am facing similar issue with ionic image upload. Did you find a solution? Commented Dec 2, 2016 at 19:17
  • @aston For this problem i already to use image base 64 instead. Commented Dec 3, 2016 at 18:14
  • @raj nope i have to encode my image to base64 and send it to server instead Commented Dec 3, 2016 at 18:15
  • my issue got resolved after turning off chunedMode Commented Mar 26, 2017 at 12:46

2 Answers 2

7

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
Sign up to request clarification or add additional context in comments.

Comments

0

I also bumped into this and needed to remove the multipart header declaration. Full example:

HTML:

<input
  type="file"
  onChange={(e) => {
    if (e?.target?.files && e.target.files[0]) {
      handleImageFile(e.target.files[0]);
    }
  }}
/>

JS:

const handleImageFile = (file) => {
  const fd = new FormData();
  fd.append("user_id", 171);
  fd.append("avatar", file);
  fetch("/user/avatar/", {
    method: "POST",
    body: fd,
    headers: {
      Accept: "application/json",
      "X-Requested-With": "XMLHttpRequest",
      "X-CSRF-Token": document.querySelector("meta[name=csrf-token]")?.getAttribute("content"),
    },
  })
    .then((result) => {
      console.log(" * result", result);
    })
    .catch((err) => {
      console.warn(" * error", err);
    });
};

Controller:

def user_avatar
  user = User.find(user_avatar_params[:user_id])
  user.avatar = user_avatar_params[:avatar]
  user.save!
end

def user_avatar_params
  params.permit(:user_id, :avatar)
end

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.