The server I'm trying to upload images to is waiting for an array of files. Throughout the internet, they use several addFormDataPart as my code below:
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 only gets the last one because it checks the "file" and takes the last one because the data is not an array. The server expects data this way:
{ "file" : [Files] }
source
share