Reputation: 127
I am trying to upload image by POST multipart request which should have structure like this :
-----------------------------219391268715340 Content-Disposition: form-data; name="photos[]"; filename="DSCF0157-Laptop.JPG" Content-Type: image/jpeg
(byte-data)
My code :
MediaType mediaType = MediaType.parse("image/jpeg");
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] byteArray = stream.toByteArray();
RequestBody file=RequestBody.create(mediaType, byteArray);
map.put("form-data; name=\"photos[]\"; filename=\""+filename+".jpg",file);
I use map because of @PartMap annotation - I want to upload multiple files. My server returns http code 200 - but no files are uploaded. Api call has been tested - it works correctly if used by our web application. Any idea what I am doing wrong
Upvotes: 2
Views: 3706
Reputation: 1634
Maybe you can do that like this.
YourAPIService
@Multipart
@POST("api/image/upload")
Call<ImageUploadResponse> uploadImage(@Part("photos") List<RequestBody> imageFiles);
YourActivity
//prepare request body
List<RequestBody> images = new ArrayList<>();
for (int i = 0; i < filePath.size(); i++){
RequestBody file = RequestBody.create(MediaType.parse("image/*"), filePath.get(i);
images.add(file);
}
//call api
Call<ImageUploadResponse> call = imageUploadService.uploadImage(images);
call.enqueue(new Callback<ImageUploadResponse>() {
@Override
public void onResponse(Call<ImageUploadResponse> call,
Response<ImageUploadResponse> response) {
}
@Override
public void onFailure(Call<ImageUploadResponse> call, Throwable t) {
}
});
Upvotes: 0
Reputation: 24114
If you want to upload many files in a request using Retrofit 2, you can refer to my answer at the question below
Retrofit - Multipart request: Required MultipartFile parameter 'file' is not present
With some modifications:
WebAPIService.java:
@Multipart
@POST("/api/fileupload")
Call<ResponseBody> postFiles(@Part List<MultipartBody.Part> fileList);
FileActivity.java:
...
List<MultipartBody.Part> fileList = new ArrayList<>();
for (int i = 0; i < 2; i++){
fileList.add(body);
}
Call<ResponseBody> call = service.postFiles(fileList);
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call,
Response<ResponseBody> response) {
Log.i(LOG_TAG, "success");
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Log.e(LOG_TAG, t.getMessage());
}
});
Of course, with the above code, in fact, the same file (body) will be uploaded as 2 parts in the request. As a result, in web server, you will have 2 files with the same content, you can customize the fileList
with many different files :)
Hope it helps!
Upvotes: 2