Have the First User Create/upload 2 Books
The previous tutorials guided you through various employ cases of Retrofit and showed you opportunities to enhance the app with Retrofit's built-in functionality. This tutorial will show you how to upload a file to a backend server using the second major release of Retrofit, namely Retrofit 2.
Retrofit Serial Overview
File Upload with Retrofit ane.ten
We've already published a tutorial on how to upload files using Retrofit 1.ten. If you lot're using Retrofit 1, please follow the link.
Using Retrofit 2? This tutorial is for yous and please read on :)
Upload Files With Retrofit 2
This tutorial is intentionally separated from the already published tutorial on how to upload files with Retrofit v1, because the internal changes from Retrofit 1 to Retrofit 2 are profound and you lot need to sympathise the way Retrofit 2 handles file uploads.
Before we dive deeper into the file upload topic with Retrofit two, let's before long epitomize the previously used functionality in v1. Retrofit 1 used a class called TypedFile for file uploads to a server. This class has been removed from Retrofit 2. Farther, Retrofit ii now leverages the OkHttp library for whatever network functioning and, as a upshot, OkHttp's classes for use cases similar file uploads.
Using Retrofit two, you demand to utilise either OkHttp's RequestBody or MultipartBody.Part classes and encapsulate your file into a asking trunk. Allow'south take a look at the interface definition for file uploads.
public interface FileUploadService { @Multipart @Mail("upload") Call<ResponseBody> upload( @Part("description") RequestBody description, @Part MultipartBody.Part file ); } Allow me explain each part of the definition above. Get-go, you need to declare the entire call as @Multipart asking. Let's go on with the note for description. The description is just a string value wrapped inside a RequestBody instance. Secondly, in that location'southward another @Office within the request: the actual file. We employ the MultipartBody.Office class that allows us to send the actual file proper noun as well the binary file data with the asking. Yous'll run into how to create the file object correctly within the following section.
Android Client Lawmaking
At this point, you've divers the necessary service interface for Retrofit. At present you lot tin can move on and impact the actual file upload. We'll use the ServiceGenerator class which generates a service customer. We've introduced the ServiceGenerator class in the creating a sustainable Android client tutorial earlier in this series.
The following lawmaking snippet shows the uploadFile(Uri fileUri) method taking the file's uri as a parameter. If you're starting an intent to choose a file, you'll return within the onActivityResult() method of Android's lifecycle. In this method, yous tin get the file'due south uri and that's exactly what you'll use to upload the file within the uploadFile method.
individual void uploadFile(Uri fileUri) { // create upload service client FileUploadService service = ServiceGenerator.createService(FileUploadService.course); // https://github.com/iPaulPro/aFileChooser/blob/master/aFileChooser/src/com/ipaulpro/afilechooser/utils/FileUtils.java // utilise the FileUtils to get the bodily file past uri File file = FileUtils.getFile(this, fileUri); // create RequestBody instance from file RequestBody requestFile = RequestBody.create( MediaType.parse(getContentResolver().getType(fileUri)), file ); // MultipartBody.Part is used to transport also the actual file name MultipartBody.Part trunk = MultipartBody.Part.createFormData("flick", file.getName(), requestFile); // add another part within the multipart asking String descriptionString = "hello, this is description speaking"; RequestBody description = RequestBody.create( okhttp3.MultipartBody.FORM, descriptionString); // finally, execute the request Call<ResponseBody> telephone call = service.upload(description, body); call.enqueue(new Callback<ResponseBody>() { @Override public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { Log.v("Upload", "success"); } @Override public void onFailure(Phone call<ResponseBody> call, Throwable t) { Log.e("Upload error:", t.getMessage()); } }); } The snippet above shows y'all the lawmaking to initialize the payload (body and description) and how to use the file upload service. As already mentioned, the RequestBody grade is from OkHttp and used for the description. Its .create() method requires two parameters: first, the media type, and 2d, the bodily information. The media type for the description can but exist OkHttp's constant for multipart requests: okhttp3.MultipartBody.FORM. The media type for the file should ideally be the actual content-type. For instance, a PNG prototype should have prototype/png. Our lawmaking snippet above figures out the content type with the getContentResolver().getType(fileUri) telephone call and so parses the result into OkHttp'south media type with MediaType.parse().
Likewise the description, you lot'll add the file wrapped into a MultipartBody.Part instance. That'due south what yous need to utilise to accordingly upload files from customer-side. Farther, you tin can add the original file proper name inside the createFormData() method and reuse it on your backend.
Think the Content-Blazon
Please go on an centre on Retrofit'south content blazon. If yous intercept the underlying OkHttp customer and modify the content type to awarding/json, your server might have issues with the deserialization process. Make sure you're not defining the header indicating you're sending JSON data, only multipart/form-data.
Next: Upload Files with Progress Updates
If y'all upload files in the foreground and they are not small, you might desire to inform the user on your actions. Ideally, you would display progress updates how much yous've uploaded already. We've some other tutorial on how to upload files with progress updates.
Exemplary Hapi Server for File Uploads
If you lot already have your backend project, you lot tin can lean on the instance code beneath. We use a unproblematic hapi server with a Post route bachelor at /upload. Additionally, we tell hapi to don't parse the incoming request, considering we use a Node.js library called multiparty for the payload parsing.
Within the callback of multiparty'south parsing office, we're logging each field to show its output.
method: 'POST', path: '/upload', config: { payload: { maxBytes: 209715200, output: 'stream', parse: false }, handler: function(request, reply) { var multiparty = require('multiparty'); var course = new multiparty.Course(); grade.parse(request.payload, function(err, fields, files) { panel.log(err); console.log(fields); console.log(files); return reply(util.inspect({fields: fields, files: files})); }); } } Android client expects a return type of String, we're sending the received information every bit response. Of course your response volition and should look unlike :)
Below you can see the output of a successful request and payload parsing on server-side. The outset null is the err object. Afterwards, yous can run across the fields which is only the description every bit part of the request. And last merely not to the lowest degree, the file is available within the pic field. Here you come across our previously divers names on client side. 20160312_095248.jpg is passed as the original proper name and the actual field name is picture. For further processing, admission the uploaded image at path'south location.
Server Log for Parsed Payload
null { description: [ 'hello, this is description speaking' ] } { picture: [ { fieldName: 'picture', originalFilename: '20160312_095248.jpg', path: '/var/folders/rq/q_m4_21j3lqf1lw48fqttx_80000gn/T/X_sxX6LDUMBcuUcUGDMBKc2T.jpg', headers: [Object], size: 39369 } ] } Outlook
File uploads are an essential feature within up-to-date apps and you can integrate this feature inside your app using Retrofit. This tutorial guided yous through the necessary steps to upload a file from your Android device to your backend server.
What to look inside the next post on Retrofit? Next week you'll larn all nigh how to go back logging within Retrofit 2. Stay tuned, information technology will be a proficient shot!
Source: https://futurestud.io/tutorials/retrofit-2-how-to-upload-files-to-server
Post a Comment for "Have the First User Create/upload 2 Books"