Retrofit Tutorial - How to Upload Files to Server

  Рет қаралды 81,426

Future Studio

Future Studio

7 жыл бұрын

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:
►futurestud.io/tutorials/retro...
Watch 20+ Retrofit videos in our playlist here:
► • Android Retrofit Tutor...
----------------------------------------
Our book on Retrofit is also available on leanpub:
►leanpub.com/retrofit-love-wor...
----------------------------------------
Future Studio is helping 5,000+ users daily to solve Android and Node.js problems with 320+ written tutorials and videos. We’re on a mission to provide new in-depth content every week.
Checkout 320+ technical in-depth tutorials:
►futurestud.io
Subscribe for two new videos every week:
►kzfaq.info...
----------------------------------------
Follow us on social media to get updates on new content:
► / futurestud_io
► / futurestudiouniversity
►plus.google.com/+FutureStudio...
----------------------------------------
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.
Let's call the description "Test123" and select a file, what will just be a retrofit book cover and as you can see the API breakpoint triggered and we have here our request payload which includes the description "Test123" and also the photo object. As you can see here's Retrofit.png and it actually contains a file. Fantastic.
In future videos we will show you how you can upload multiple files and how to set more than just one description.

Пікірлер: 93
@hungrysquirrei6961
@hungrysquirrei6961 3 жыл бұрын
Very nice tutorial, I like how you explain the code, instead of just coding without any commentary!
@bacassf8477
@bacassf8477 5 жыл бұрын
Nice tutorial :) Thank you.
@kishansharma5291
@kishansharma5291 5 жыл бұрын
Thanks for Helping me, and also this is great tutorial to image uploading by retrofit.
@abhishekjha6550
@abhishekjha6550 5 жыл бұрын
How to create API to test these integrations
@anissanaa3050
@anissanaa3050 3 жыл бұрын
Thanks , very interested video !!
@aamilsilawat3069
@aamilsilawat3069 5 жыл бұрын
Great Job 👍🏻
@fuadreza3090
@fuadreza3090 3 жыл бұрын
Thanks, you help a lot.. :)
@solomonaryeetey7370
@solomonaryeetey7370 6 жыл бұрын
I just subscribed!!!
@SussanRai
@SussanRai 6 жыл бұрын
can u show me in the json format after i upload the files and description to the server??
@eduboonlovetolearnpvtltd.8202
@eduboonlovetolearnpvtltd.8202 3 жыл бұрын
Thank you sir.Very helpfull
@swazza3071
@swazza3071 7 жыл бұрын
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)
@DiegoPenteado
@DiegoPenteado 6 жыл бұрын
Great tutorial! Thank you!
@amitaiefrati4111
@amitaiefrati4111 4 жыл бұрын
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?
@RohitSharma-jb1mx
@RohitSharma-jb1mx 5 жыл бұрын
Sir, How to compress the image before uploading if we follow this way ?
@lawrencekatuva8735
@lawrencekatuva8735 3 жыл бұрын
FileUtils class does not have the method getPath() .....
@ASININEMedia
@ASININEMedia 4 жыл бұрын
Hi, when uploading files greater than 4 mb it's showing socket timeout exception. Please help
@adityakumar7318
@adityakumar7318 4 жыл бұрын
Can you please help me with directly capturing Image from camere, and uploading to server. Thankyou
@techspartans4333
@techspartans4333 5 жыл бұрын
how to upload video and user data through retrofit, i am facing problem, kindly help me
@nileshhingu7338
@nileshhingu7338 5 жыл бұрын
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
@artabandhumohanty9087
@artabandhumohanty9087 4 жыл бұрын
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.
@faridfathy7195
@faridfathy7195 6 жыл бұрын
how can i send an annotation like @POST("upload") Call upload(@Part("user-file") MultipartBody.Part file);
@ahkamkhalaf7082
@ahkamkhalaf7082 6 жыл бұрын
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
@croptv7093
@croptv7093 6 жыл бұрын
It is not clear what is RequestBody MultipartBody, what are these classes and where are they from (
@smartliga8623
@smartliga8623 6 жыл бұрын
Please give an example File image = new File (????) how to put the file in those brackets??
@jimenaleonbm
@jimenaleonbm 5 жыл бұрын
Hi, How can do I work with pdf files ?
@shanigupta9533
@shanigupta9533 6 жыл бұрын
pause and resume uploaded process...how to achieve it
@justicearthur8613
@justicearthur8613 4 жыл бұрын
Please I cannot find the github files for this particular video and the previous ones
@Hrvoje1996
@Hrvoje1996 7 жыл бұрын
Hej, First of all great tutorial series of videos, But I am interested in downloading files. Are you planning to do the downloading of files any time soon ?
@FutureStudio
@FutureStudio 7 жыл бұрын
A little late, but we have a video on downloading files with Retrofit: kzfaq.info/get/bejne/e5uWrbF5r6rPqoE.html
@faniaindah7818
@faniaindah7818 7 жыл бұрын
haii.. i wanto to ask something, is the uploaded file only image only ? Thank's
@FutureStudio
@FutureStudio 7 жыл бұрын
Hi, good question! The video shows how to upload an image, but you can use the code to upload any other kind of file, too :)
@faniaindah7818
@faniaindah7818 7 жыл бұрын
okaii.. thank's :)
@JohnOtaalo
@JohnOtaalo 7 жыл бұрын
Hi. Great tutorial. I have a tiny issue with my code. When I upload the file, I get a timeout exception thrown. I am not sure what may be wrong as I have done the same thing as you. Other than the server (Mine is a PHP server)
@FutureStudio
@FutureStudio 7 жыл бұрын
Does the server respond to the request? Does the server work with other clients?
@JohnOtaalo
@JohnOtaalo 7 жыл бұрын
Yes it does. I am able to send the normal form data. Problem comes when I add files
@0vuln
@0vuln 5 жыл бұрын
Hello !Great tuto!How to send image uploaded from camera to the server?Thanks
@adamfils
@adamfils 4 жыл бұрын
get the uri data from onActivityResult Method
@hailajoaca3780
@hailajoaca3780 7 жыл бұрын
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 . :(
@hailajoaca3780
@hailajoaca3780 7 жыл бұрын
Yes , I tried to find a tutorial how I could do it for 1 week , can't find anything . I don't know how to make the API to receive the file . I want people to be able to upload a photo from their android phone , along with description and then to show it back via it's URL with Picasso . By the way you are awesome, thank you for creating Retrofit and Picasso !
@aminraphael4734
@aminraphael4734 4 жыл бұрын
Hi , Can anyone give me a sample server-side(PHP or NodeJS) code ?? Thank you :)
@mohammadtaqi4051
@mohammadtaqi4051 3 жыл бұрын
How can I get that file using php ?
@shanigupta9533
@shanigupta9533 6 жыл бұрын
Upload file with progressbar... Can you make a app
@binary2quantum26
@binary2quantum26 5 жыл бұрын
how can i upload any file like pdf,jpg,docx,xlsx into server
@adamfils
@adamfils 4 жыл бұрын
Create an implicit intent and capture the uri in onActivityResult You then get the file via the captured URI and the rest can be followed from the video.
@lester8430
@lester8430 2 жыл бұрын
Sir, where can I turn on zee captions. May God forgive me.
@alertys
@alertys 6 жыл бұрын
Is it possible to download the code used in this video?
@FutureStudio
@FutureStudio 6 жыл бұрын
Nope.
@haykabelyan8524
@haykabelyan8524 6 жыл бұрын
Excuse me, how can I get the link of the image after it is uploaded?
@FutureStudio
@FutureStudio 6 жыл бұрын
That depends on the server/API.
@haykabelyan8524
@haykabelyan8524 6 жыл бұрын
Kindly check your FB page, I have messaged you.
@rankogudalovic4245
@rankogudalovic4245 3 жыл бұрын
And what is FileUtils class, where is it??
@iann189
@iann189 7 жыл бұрын
I have a problem with FIleUtils and is there any way to access the file.
@FutureStudio
@FutureStudio 7 жыл бұрын
What's your problem?
@swazza3071
@swazza3071 7 жыл бұрын
FileUtil depends on another package: import com.ianhanniballake.localstorage.LocalStorageProvider; which is again depended on: import com.ipaulpro.afilechooser.R; Moreover, they don't work below level API 19. I am currently using API 15 onwards. Please share some lights. Thanks in advance.
@FutureStudio
@FutureStudio 7 жыл бұрын
You don't need to use the FileUtils class. You can access the file any way you want to. It's just important that you have a loaded File object at the end!
@swazza3071
@swazza3071 7 жыл бұрын
Tried wrapping bitmap Returning null file using - File file = FileUtils.getFile(this, fileUri); I have shared more details in futurestudio facebook chat
@abhishekpanchal2297
@abhishekpanchal2297 4 жыл бұрын
@@FutureStudioKindly elaborate, what do you mean by "having loaded File object at the end"? Thanks in advance
@thetechroticslab5753
@thetechroticslab5753 2 жыл бұрын
can i get the github link of this project?
@ABHISHAKESINGHIASPREP
@ABHISHAKESINGHIASPREP 6 жыл бұрын
Sir please tell me what is fileutils class
@FutureStudio
@FutureStudio 6 жыл бұрын
It's linked in the pinned comment on the top.
@yairccepayadiaz7026
@yairccepayadiaz7026 4 жыл бұрын
I can't use getContentResolver().getType
@user-vn4fs2bc4j
@user-vn4fs2bc4j Жыл бұрын
It send just Media-type How can I send pdf file?
@jeetshah8513
@jeetshah8513 2 жыл бұрын
How to install FileUtils ?
@FutureStudio
@FutureStudio 7 жыл бұрын
Hi, the FileUtils method is from this class: github.com/iPaulPro/aFileChooser/blob/master/aFileChooser/src/com/ipaulpro/afilechooser/utils/FileUtils.java It's just a wrapper to catch differences in various Android versions. You don't need to use it. if you do, you should replace the LocalStorageProvider import: See here for an example: stackoverflow.com/a/34860827/814353
@abdulwahid_mohammed
@abdulwahid_mohammed 6 жыл бұрын
what is the alternative of not using FileUtils to do this lesson?
@viveksai7954
@viveksai7954 6 жыл бұрын
Hey bud.. can FileUtils work without the inclusion of LocalStorageProvider?
@viveksai7954
@viveksai7954 6 жыл бұрын
the fileUri passed as an argument is localStorage uri?
@viveksai7954
@viveksai7954 6 жыл бұрын
Hello.... if the fileUri is the localStorage uri...then File mainFile=new File(fileUri.getPath()) should serve the need..for me it dint work here but in all my firebase code in works fine..
@caiozowyecamachocabral5413
@caiozowyecamachocabral5413 5 жыл бұрын
You say: "You don't need to use it" What do I use instead? Simply don't write the code? shit! Why it's always so hard to implement every little shit!?
@ibrahimnada4702
@ibrahimnada4702 6 жыл бұрын
FileUtils Where Can i get that :/
@FutureStudio
@FutureStudio 6 жыл бұрын
Literally the first link in the comments.
@ahmedabdeen1095
@ahmedabdeen1095 6 жыл бұрын
Hi, If someone faces a problem with the server side code.. Here is an example in php:
@smartliga8623
@smartliga8623 6 жыл бұрын
To run File image = new File (filePath) you need to know real file path. Code below gives you real path without FileUtils monster. public static String getRealPathFromURI_API19_and_later(Context context, Uri uri){ String filePath = ""; String wholeID = DocumentsContract.getDocumentId(uri); // Split at colon, use second item in the array String id = wholeID.split(":")[1]; String[] column = { MediaStore.Images.Media.DATA }; // where id is equal to String sel = MediaStore.Images.Media._ID + "=?"; Cursor cursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, column, sel, new String[]{ id }, null); int columnIndex = cursor.getColumnIndex(column[0]); if (cursor.moveToFirst()) { filePath = cursor.getString(columnIndex); } cursor.close(); return filePath; }
@DeadBreaker3004
@DeadBreaker3004 4 жыл бұрын
u r my angel, thank you so much, my God.
@elviss911
@elviss911 4 жыл бұрын
without api this tutorial is bad
@konn81
@konn81 Жыл бұрын
kotlin?
@helpyourlovedones2849
@helpyourlovedones2849 6 жыл бұрын
you mumble way to much. Slow down, speak clearly!
@parvezhafeez7174
@parvezhafeez7174 4 жыл бұрын
Improve your audio, don't get into the mic, even your breathing is audible, and that creepy keyboard sound is so irritating as well. And finally you need to work on your pronunciation, its not good. Although lecture was informative, but so need to be audio.
@endy240
@endy240 Жыл бұрын
Its Great series.Thank you!!!! But i have a problem: "java.io.FileNotFoundException: /storage/emulated/0 / Pictures/.thumbnails/66.jpg: open failed: ENOENT (No such file or directory)"
Retrofit Tutorial - Passing Multiple Parts Along a File with @PartMap
10:49
Retrofit Tutorial - How to Upload Multiple Files to Server
7:55
Future Studio
Рет қаралды 29 М.
Why Is He Unhappy…?
00:26
Alan Chikin Chow
Рет қаралды 68 МЛН
Stay on your way 🛤️✨
00:34
A4
Рет қаралды 26 МЛН
Pleased the disabled person! #shorts
00:43
Dimon Markov
Рет қаралды 31 МЛН
Retrofit Tutorial - Getting Started and Creating an Android Client
11:59
Retrofit Tutorial - Synchronous and Asynchronous Requests
6:21
Future Studio
Рет қаралды 30 М.
How To Upload Large Files To Web Server  in Android
10:39
Filip Vujovic
Рет қаралды 58 М.
Retrofit Tutorial - Send Objects In Request Body
9:13
Future Studio
Рет қаралды 76 М.
UPLOADING PDF FILE TO SERVER USING RETROFIT IN ANDROID
17:09
Bamidele Oguntuga
Рет қаралды 20 М.
Angular Signals: What? Why? and How?
27:08
Deborah Kurata
Рет қаралды 57 М.
Axios - Download Files & Images in Node.js
9:46
Future Studio
Рет қаралды 58 М.
Immutable Linux, without the hassle? Vanilla OS 2 Orchid
16:10
The Linux Experiment
Рет қаралды 10 М.
Storing Images in S3 from Node Server
39:59
Sam Meech-Ward
Рет қаралды 86 М.
Retrofit Tutorial - How to Download Files from Server
15:12
Future Studio
Рет қаралды 34 М.
Лучший браузер!
0:27
Honey Montana
Рет қаралды 1,1 МЛН
My iPhone 15 pro max 😱🫣😂
0:21
Nadir Show
Рет қаралды 1,8 МЛН
Какой ноутбук взять для учёбы? #msi #rtx4090 #laptop #юмор #игровой #apple #shorts
0:18
Yanlışlıkla Telefonumu Parçaladım!😱
0:18
Safak Novruz
Рет қаралды 817 М.
Bluetooth connected successfully 💯💯
0:16
Blue ice Comedy
Рет қаралды 1,6 МЛН