Retrofit 2 file down/upload Retrofit 2 file down/upload android android

Retrofit 2 file down/upload


For downloading, you can use ResponseBody as your return type --

@GET("documents/checkout")@Streamingpublic Call<ResponseBody> checkout(@Query("documentUrl") String documentUrl, @Query("accessToken") String accessToken, @Query("readOnly") boolean readOnly);

and you can get the ResponseBody input stream in your call back --

Call<ResponseBody> call = RetrofitSingleton.getInstance(serverAddress)            .checkout(document.getContentUrl(), apiToken, readOnly[i]);call.enqueue(new Callback<ResponseBody>() {        @Override        public void onResponse(Response<ResponseBody> response,                Retrofit retrofit) {            String fileName = document.getFileName();            try {                InputStream input = response.body().byteStream();                //  rest of your code

Your upload looks okay at first glance if you server handles multipart messages correctly. Is it working? If not, can you explain the failure mode? You also might be able to simplify by not making it multipart. Remove the @Multipart annotation and convert @Path to @Body --

@POST("documents/checkin")public Call<String> checkin(@Query("documentId") String documentId, @Query("name") String fileName, @Query("accessToken") String accessToken, @Body RequestBody file);


I am using retrofit 2.0.0-beta2 and I had an issue uploading image by using multipart request. I solved it by using this answer: https://stackoverflow.com/a/32796626/2915075

The key for me was to use standard POST with MultipartRequestBody instead of @Multipart annotated request.

Here is my code:

Retrofit service class

@POST("photo")Call<JsonElement> uploadPhoto(@Body RequestBody imageFile, @Query("sessionId"));

Usage from activity, fragment:

RequestBody fileBody = RequestBody.create(MediaType.parse("image/jpeg"), imageFile);MultipartBuilder multipartBuilder = new MultipartBuilder();multipartBuilder.addFormDataPart("photo", imageFile.getName(), fileBody);RequestBody fileRequestBody = multipartBuilder.build();//callmRestClient.getRetrofitService().uploadProfilePhoto(fileRequestBody, sessionId);


i have the same problems, and i found a solution to upload files, that described hereIs it possible to show progress bar when upload image via Retrofit 2