我尝试上传图片的服务器正在等待一个文件数组。在互联网上,他们使用多个addFormDataPart作为我的代码:
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();
问题是服务器只收到最后一个,因为它检查" file"并采用最后一个因为数据不是数组。服务器以这种方式期望数据:
{ "file" : [Files] }
答案 0 :(得分:2)
我的猜测是你需要将多部分数据字段的名称更改为file[]
,因为服务器需要一组图像而不是一个(最后一个)图像:
buildernew.addFormDataPart("file[]", image.getName(), imageBody);