前提・実現したいこと
タイトルの通り、retrofit2を用いて画像をアップロードしたいです。
以下のリクエストパラメータにてリクエストを行っていますが、
サーバー側のログを確認するとuser配下が欠落し({"users"=>"{}"})、
正常にリクエストが出来ておりません。
user (必須項目)
thumbnail (File)
該当のソースコード
public interface User {
@Multipart
@PATCH({エンドポイント})
Call<JsonObject> uploadImage(
@Header("Authorization") String authToken,
@PartMap Map<String, Map<String, RequestBody>> body
);
}
private User buildClient() {
User result;
Retrofit retrofit = new Retrofit.Builder() .baseUrl(ApiUtils.HOST) .addConverterFactory(GsonConverterFactory.create()) .client(new OkHttpClient.Builder().build()) .build(); result = retrofit.create(UserApi.class); return result;
}
public void uploadImage() {
Map<String, Map<String, RequestBody>> body = new HashMap<>();
Map<String, RequestBody> image = new HashMap<>(); String filePath = "/storage/emulated/0/Download/m_1.jpg"; File file = new File(filePath); RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file); image.put("image\"; filename=\"m_1.jpg\"", requestFile); body.put("user", image); Call<JsonObject> call = buildClient().uploadImage(mAuthToken, body); call.enqueue(new Callback<JsonObject>() { @Override public void onResponse(Call<JsonObject> call, Response<JsonObject> response) { boolean isSuccessful = response.isSuccessful(); int statusCode = response.code(); if (isSuccessful) { } else { } } @Override public void onFailure(Call<JsonObject> call, Throwable t) { call.cancel(); } });
}
試したこと
上記のように入れ子にしないければ欠落はしませんが、
パラメータが不正のためエラーとなります。
(ステータスコード:400)
public interface User {
@Multipart
@PATCH({エンドポイント})
Call<JsonObject> uploadImage(
@Header("Authorization") String authToken,
@PartMap Map<String, RequestBody> body
);
}
public void uploadImage() {
Map<String, RequestBody> image = new HashMap<>(); String filePath = "/storage/emulated/0/Download/m_1.jpg"; File file = new File(filePath); RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file); image.put("image\"; filename=\"m_1.jpg\"", requestFile); Call<JsonObject> call = buildClient().uploadImage(mAuthToken, image); call.enqueue(new Callback<JsonObject>() {
~ 以下、省略 ~
補足情報(FW/ツールのバージョンなど)
android studio:3.2
retrofit:2.4.0
あなたの回答
tips
プレビュー