ionicorn ionicorn - 1 month ago 14
Java Question

Upload an array of images using OkHTTP

The server to which I am trying to upload images is waiting for an array of Files. Everywhere over the internet they use multiple addFormDataPart as my code bellow:

final OkHttpClient client = new OkHttpClient();
MediaType MEDIA_TYPE_PNG;

MultipartBody.Builder buildernew = new MultipartBody.Builder().setType(MultipartBody.FORM);
for (Image image : media) {
MEDIA_TYPE_PNG = image.getName().endsWith("png") ? MediaType.parse("image/png") : MediaType.parse("image/jpeg");
RequestBody imageBody = RequestBody.create(MEDIA_TYPE_PNG, image.getPath());
buildernew.addFormDataPart("file", image.getName(), imageBody);
}
MultipartBody requestBody = buildernew.build();
final Request request = new Request.Builder()
.addHeader("authorization", "Bearer " + Credentials.getAuthToken(mContext))
.url(url)
.post(requestBody)
.build();
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
Response response = client.newCall(request).execute();
if (response.message().contentEquals("OK") && response.code() == 200) {
System.out.println(response.body().string());
}
System.out.println(response.body().string());
} catch (Exception e) {
Log.e(TAG, e.getMessage());
}
}
});
thread.start();


The problem is that the server receives only the last one because it checks for "file" and takes the last one because the data is not an array. The server expect the data in this way:

{ "file" : [Files] }

Answer

My guess is that you need to change the name of the multipart data field to file[] since the server expects an array of images and not a single (last) one:

buildernew.addFormDataPart("file[]", image.getName(), imageBody);
Comments