Wor Dunable to Upload to This Server

The previous tutorials guided you through diverse employ cases of Retrofit and showed you opportunities to raise the app with Retrofit's built-in functionality. This tutorial volition show you how to upload a file to a backend server using the 2nd major release of Retrofit, namely Retrofit two.

Retrofit Series Overview

File Upload with Retrofit 1.10

We've already published a tutorial on how to upload files using Retrofit 1.10. If y'all're using Retrofit 1, please follow the link.

Using Retrofit 2? This tutorial is for you 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, considering the internal changes from Retrofit 1 to Retrofit 2 are profound and you need to empathize the fashion Retrofit two handles file uploads.

Before we dive deeper into the file upload topic with Retrofit 2, let'due south shortly epitomize the previously used functionality in v1. Retrofit one used a grade chosen TypedFile for file uploads to a server. This class has been removed from Retrofit ii. Farther, Retrofit 2 now leverages the OkHttp library for any network operation and, as a result, OkHttp'southward classes for use cases similar file uploads.

Using Retrofit 2, you need to utilise either OkHttp'due south RequestBody or MultipartBody.Part classes and encapsulate your file into a asking body. Allow's have a look at the interface definition for file uploads.

          public interface FileUploadService {       @Multipart     @Postal service("upload")     Call<ResponseBody> upload(         @Role("clarification") RequestBody description,         @Part MultipartBody.Function file     ); }                  

Permit me explain each part of the definition in a higher place. First, yous need to declare the entire call as @Multipart asking. Permit'south keep with the annotation for description. The description is just a string value wrapped inside a RequestBody example. Secondly, there's another @Office within the request: the actual file. Nosotros use the MultipartBody.Office class that allows us to ship the actual file name as well the binary file data with the asking. You'll see how to create the file object correctly within the following section.

Android Customer Code

At this indicate, you've defined the necessary service interface for Retrofit. Now you tin move on and affect the actual file upload. Nosotros'll utilize 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 post-obit lawmaking snippet shows the uploadFile(Uri fileUri) method taking the file's uri every bit a parameter. If you're starting an intent to choose a file, you'll return within the onActivityResult() method of Android'south lifecycle. In this method, yous tin get the file's uri and that'south exactly what you'll use to upload the file within the uploadFile method.

          private void uploadFile(Uri fileUri) {       // create upload service client     FileUploadService service =             ServiceGenerator.createService(FileUploadService.class);      // https://github.com/iPaulPro/aFileChooser/hulk/chief/aFileChooser/src/com/ipaulpro/afilechooser/utils/FileUtils.coffee     // use the FileUtils to get the actual file by uri     File file = FileUtils.getFile(this, fileUri);      // create RequestBody instance from file     RequestBody requestFile =             RequestBody.create(                          MediaType.parse(getContentResolver().getType(fileUri)),                          file              );      // MultipartBody.Role is used to send likewise the actual file name     MultipartBody.Part body =             MultipartBody.Part.createFormData("picture", file.getName(), requestFile);      // add together some other office within the multipart request     String descriptionString = "hello, this is clarification speaking";     RequestBody description =             RequestBody.create(                     okhttp3.MultipartBody.FORM, descriptionString);      // finally, execute the request     Telephone call<ResponseBody> phone call = service.upload(description, body);     call.enqueue(new Callback<ResponseBody>() {         @Override         public void onResponse(Telephone call<ResponseBody> call,                                Response<ResponseBody> response) {             Log.5("Upload", "success");         }          @Override         public void onFailure(Call<ResponseBody> call, Throwable t) {             Log.e("Upload error:", t.getMessage());         }     }); }                  

The snippet to a higher place shows yous the code to initialize the payload (body and description) and how to use the file upload service. Equally already mentioned, the RequestBody class is from OkHttp and used for the description. Its .create() method requires two parameters: commencement, the media blazon, and second, the actual information. The media type for the description can simply be OkHttp's abiding for multipart requests: okhttp3.MultipartBody.FORM. The media type for the file should ideally be the bodily content-blazon. For instance, a PNG prototype should have image/png. Our lawmaking snippet above figures out the content blazon with the getContentResolver().getType(fileUri) phone call and then parses the result into OkHttp's media type with MediaType.parse().

Also the description, you lot'll add together the file wrapped into a MultipartBody.Part case. That's what you need to use to appropriately upload files from client-side. Further, you can add the original file name within the createFormData() method and reuse it on your backend.

Retrieve the Content-Type

Please go along an eye on Retrofit'southward content type. If you intercept the underlying OkHttp client and alter the content type to application/json, your server might take problems with the deserialization process. Make sure you're not defining the header indicating you're sending JSON data, but multipart/form-data.

Next: Upload Files with Progress Updates

If you upload files in the foreground and they are not small-scale, you might want to inform the user on your actions. Ideally, you would brandish progress updates how much you've uploaded already. We've some other tutorial on how to upload files with progress updates.

Exemplary Hapi Server for File Uploads

If yous already take your backend project, y'all can lean on the example code beneath. We use a uncomplicated hapi server with a Post route available at /upload. Additionally, we tell hapi to don't parse the incoming request, because nosotros employ a Node.js library chosen multiparty for the payload parsing.

Within the callback of multiparty'due south parsing role, we're logging each field to testify its output.

          method: 'Mail',   path: '/upload',   config: {       payload: {         maxBytes: 209715200,         output: 'stream',         parse: false     },     handler: part(request, respond) {         var multiparty = require('multiparty');         var grade = new multiparty.Form();         grade.parse(request.payload, role(err, fields, files) {             console.log(err);             console.log(fields);             panel.log(files);              return reply(util.inspect({fields: fields, files: files}));         });     } }                  

Android client expects a render type of Cord, we're sending the received information as response. Of form your response will and should expect dissimilar :)

Beneath you can see the output of a successful request and payload parsing on server-side. The first null is the err object. Subsequently, you can see the fields which is but the description equally function of the asking. And last but not least, the file is available within the picture field. Hither y'all run into our previously defined names on client side. 20160312_095248.jpg is passed equally the original name and the actual field name is moving-picture show. For further processing, access the uploaded epitome at path'southward location.

Server Log for Parsed Payload

          naught   { description: [ 'hello, this is description speaking' ] } { pic:    [ { fieldName: 'motion-picture show',        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-appointment apps and you can integrate this feature within your app using Retrofit. This tutorial guided you through the necessary steps to upload a file from your Android device to your backend server.

What to wait inside the next post on Retrofit? Next week you'll learn all most how to get back logging inside Retrofit ii. Stay tuned, it will exist a adept shot!


starkeydamend.blogspot.com

Source: https://futurestud.io/tutorials/retrofit-2-how-to-upload-files-to-server

0 Response to "Wor Dunable to Upload to This Server"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel