我的工作是在我的应用中启用文件上传,其中使用:React,Redux,Redux-Form,React-dropzone。
我认为问题是我的API调用未使用'content-type': 'multipart/form-data'
以下是我将react-dropzone文件上传到我的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;
});
}
在Chrome网络标签中,我看到:
content-type:application/json,multipart/form-data
然而,由于API(Rails 5 + Carrierwave)无法保存文件,它仍然无法正常工作。我做错了什么?
Rails控制器:
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
....
日志:
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)