3

My I'm working to enable file uploads within my app which uses: React, Redux, Redux-Form, React-dropzone.

I believe the issue is my API call is not using 'content-type': 'multipart/form-data'

Here is my code to post the react-dropzone file upload to my API (Rails 5).

  static updateProfile(profile, user_id) {
    const request = new Request(`http://localhost:4300/api/v1/profiles/${user_id}`, {
      method: 'PUT',
      headers: new Headers({
        'Authorization': getBearerToken(),
        'Accept'       : 'application/json',
        'Content-Type' : 'application/json',
        '_method'      : 'put',
        'content-type': 'multipart/form-data'        
      }),
      body: JSON.stringify({profile: profile})
    });

    return fetch(request).then(response => {
      return response.json();
    }).catch(error => {
      return error;
    });
  }

In the chrome network tab I see:

content-type:application/json,multipart/form-data

However it still isn't working as the API (Rails 5 + Carrierwave) is unable to save the file. What am I doing wrong?

Rails Controller:

  def update
    if current_user.id = params[:id]
      current_user.update(
        avatar: params[:profile][:files][0][:preview],
        first_name: params[:profile][:first_name],
        last_name: params[:profile][:last_name]
      )
    end
    ....

Log:

0:51:20 api.1  | Started PUT "/api/v1/profiles/3" for 127.0.0.1 at 2017-06-24 20:51:20 -0700
20:51:20 api.1  | Processing by Api::V1::ProfilesController#update as JSON
20:51:20 api.1  |   Parameters: {"profile"=>{"first_name"=>"XXX", "last_name"=>"XXXX", "files"=>[{"preview"=>"blob:http://localhost:4400/199b0d66-080e-4ea9-aabb-8640e98d1fc4"}]}, "id"=>"3"}
20:51:20 api.1  | XXXX
20:51:20 api.1  | [<ActionController::Parameters {"preview"=>"blob:http://localhost:4400/199b0d66-080e-4ea9-aabb-8640e98d1fc4"} permitted: false>]
20:51:20 api.1  | "blob:http://localhost:4400/199b0d66-080e-4ea9-aabb-8640e98d1fc4"
20:51:20 api.1  |   User Load (1.0ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1 LIMIT $2  [["id", 3], ["LIMIT", 1]]
20:51:20 api.1  |    (0.3ms)  BEGIN
20:51:20 api.1  |   SQL (0.7ms)  UPDATE "users" SET "current_sign_in_at" = $1, "last_sign_in_at" = $2, "sign_in_count" = $3, "updated_at" = $4 WHERE "users"."id" = $5  [["current_sign_in_at", "2017-06-25 03:51:20.650891"], ["last_sign_in_at", "2017-06-25 03:49:18.446775"], ["sign_in_count", 439], ["updated_at", "2017-06-25 03:51:20.652187"], ["id", 3]]
20:51:20 api.1  |    (0.7ms)  COMMIT
20:51:20 api.1  |    (1.4ms)  BEGIN
20:51:20 api.1  |   SQL (1.2ms)  UPDATE "users" SET "avatar" = $1, "updated_at" = $2 WHERE "users"."id" = $3  [["avatar", nil], ["updated_at", "2017-06-25 03:51:20.660205"], ["id", 3]]
20:51:20 api.1  |    (1.2ms)  COMMIT
20:51:20 api.1  | Completed 200 OK in 18ms (Views: 0.3ms | ActiveRecord: 6.5ms)
Sebastián Palma
  • 32,692
  • 6
  • 40
  • 59
AnApprentice
  • 108,152
  • 195
  • 629
  • 1,012

0 Answers0