ionicorn ionicorn - 1 year ago 101
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();

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 =;
final Request request = new Request.Builder()
.addHeader("authorization", "Bearer " + Credentials.getAuthToken(mContext))
Thread thread = new Thread(new Runnable() {
public void run() {
try {
Response response = client.newCall(request).execute();
if (response.message().contentEquals("OK") && response.code() == 200) {
} catch (Exception e) {
Log.e(TAG, e.getMessage());

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 Source

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);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download