Retrofit Tutorial — How to Upload Files to Server

preview_player
Показать описание
In this video you'll learn how to upload files to a server with Retrofit.

Tip: turn on subtitles to deal with my accent. A shortened transcript is also available below.

Find the tutorial for an easy read here:

Watch 20+ Retrofit videos in our playlist here:

----------------------------------------

Our book on Retrofit is also available on leanpub:

----------------------------------------

Checkout 320+ technical in-depth tutorials:

Subscribe for two new videos every week:

----------------------------------------

Follow us on social media to get updates on new content:

----------------------------------------

In this video we will look at so-called multi-part requests, which is more or less a fancy word for file upload requests. Once you have seen a bit of theory behind multi-part requests you'll create them this Retrofit. Specifically we will implement an app which let's the user upload photos with the description to the server. We start at the beginning and we will look at every necessary step to upload files from an Android app.
You will learn about new annotations like @MultiPart and @Part. You'll also get to know the request and response body classes and finally OkHttp's MultipartBody.Part class Multi-part requests are HTTP requests which are usually used if you're trying to send files to the server.
The file can be audio, video, photo, or any kind of binary data. As always when implementing a new endpoint with Retrofit we will start with describing the endpoint in the interface class. You're going to add an additional endpoint to upload a file. When you're sending data even if it's files, it needs to be POST or PUT request. We can do that with the @MultiPart annotation. Retrofit now knows that this request is multi-part request.
In our demo case we will simply send a description and a photo file. Consequently, we need to annotate every parameter with @Part annotation. That's not enough, we also need to specify what types the parameters are. Finally the @Part annotation offers you to name the part and set the encoding.
As with any other Retrofit request you can pass null values if something should be emitted from the request. If the user doesn't have a description you can simply pass null. This would also work for the photo parameter even though this upload endpoint wouldn't make much sense then.
The final thing you have to add is a return type. This really depends on the API and use case. In our demo API you won't return anything meaningful. So we just keep it unspecific with the ResponseBody class. You won't get any typed Java objects but you can still access general information like the status code or also the response body itself as a string.
Our main activity only has a bunch of code to deal with the permissions, file selection in views. The interesting part is the uploadFile method, which takes the file URI. Basically this function gets called when the user gave all the permissions and selected a file to upload.
First up is a string description of the photo. As we have specified in the API endpoint description we need to create and pass the RequestBody object. The RequestBody class offers a static create() method, which we'll use now.The first parameter is the media type of the RequestBody This needs to be multipart-form when sending additional data along with the file.
The second parameter is our file. This is a two-step process. First, we're also creating a RequestBody for the file again using the RequestBody. create() method. This time the first parameter is actually the content type of the file. We will use a ContentResolver to get the type dynamically and then parse the content type in OkHttp's media type. Getting a file object from a file URI surprisingly difficult and really depends on a variety of things like Android OS version, phone model, and so on. I'm using a FileUtils class.
Last, but not least, we will pass a file part object.
In future videos we will show you how you can upload multiple files and how to set more than just one description.
Рекомендации по теме
Комментарии
Автор

Very nice tutorial, I like how you explain the code, instead of just coding without any commentary!

hungrysquirrei
Автор

FileUtils not working, need to send image in API 15 onwards. Any way around to fix it?

public class LocalStorageProvider extends DocumentsProvider (DocumentsProvider is added API level 19)

swazza
Автор

can u show me in the json format after i upload the files and description to the server??

SussanRai
Автор

FileUtils class does not have the method getPath()

lawrencekatuva
Автор

Hi, when uploading files greater than 4 mb it's showing socket timeout exception. Please help

ASININEMedia
Автор

It is not clear what is RequestBody MultipartBody, what are these classes and where are they from (

croptv
Автор


It's just a wrapper to catch differences in various Android versions. You don't need to use it.

FutureStudio
Автор

Hi, If I want to upload a large file, then how can I deal with errors? Meaning if an error occurs in the middle of the upload then how can I upload only what left.
Will Multipart help with this?

amitaiefrati
Автор

is it possible to upload json file to gist, using same approach . I have tried it in similar way but i am getting error .please help.

artabandhumohanty
Автор

Please I cannot find the github files for this particular video and the previous ones

justicearthur
Автор

Sir, where can I turn on zee captions. May God forgive me.

lester
Автор

Its Great series.Thank you!!!! But i have a problem:
/storage/emulated/0 / Pictures/.thumbnails/66.jpg: open failed: ENOENT (No such file or directory)"

endy
Автор

how can i send an annotation like
@POST("upload")

faridfathy
Автор

thanks alot for the very helpful tutrail, ,i ask if i want to take the photo from the camera
, can U help me to do that

ahkamkhalaf
Автор

I want to upload image file using multipart with other param like name address and etc, please provide php side code. how to receive param using multipart

nileshhingu
Автор

I have a problem with FIleUtils and is there any way to access the file.

iann
Автор

Can you please help me with directly capturing Image from camere, and uploading to server.
Thankyou

adityakumar
Автор

Great tutorial.
But now i have problems with my web restful spring api, i don't know what should i do to expect a photo . :(

hailajoaca
Автор

Thanks for Helping me, and also this is great tutorial to image uploading by retrofit.

kishansharma
Автор

how to upload video and user data through retrofit, i am facing problem, kindly help me

techspartans