Working with Retrofit (part 2)

uploading images and files by Retrofit

Ankit Dubey
AndroidPub
Published in
2 min readJan 28, 2019

--

So, we have discussed the basic things of Retrofit in Working with Retrofit (part 1), now it is time to learn more interesting things about it.

In most of the applications we often need to upload images to server by mobile apps. These images may be one, two or many in numbers. Retrofit provides very easy way to upload images to server. We just need to follow the below steps.

For example we can take this web-service api. It accepts id, name and user_image to upload image.

First we have to define a method in RetrofitService interface that will be used to upload image. Method will be looked like this

Now we have to call this method by passing userid, name and image.

Suppose we have 3 String type instance variable as personId, personName and mCurrentPhotoPath where mCurrentPhotoPath stores the path of our image file which we want to upload. Before passing all these variables to uploadData(-,-,-) method, we have to convert them into RequestBody and Multipart.Body.Part (for image) type as follows

Finally call the method as follows

congratulations! you have successfully uploaded the image.

Still there are many things in Retrofit, one more thing i want to discuss here. Sometimes we call an API and it may take a longer time than normal and we’ll get timeout exception. In that case we can increase the time of api as follows.

We’ve already created this class in our last story Working with Retrofit (part 1)

Thank you so much. And yes if you liked the content, please hit clap :)

--

--