Galaxy File Upload Error File Size 0 Bytes
The previous tutorials guided you through various apply cases of Retrofit and showed yous opportunities to enhance the app with Retrofit'south born functionality. This tutorial will evidence you how to upload a file to a backend server using the second major release of Retrofit, namely Retrofit 2.
Retrofit Series Overview
File Upload with Retrofit i.x
We've already published a tutorial on how to upload files using Retrofit 1.x. If you'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, because the internal changes from Retrofit 1 to Retrofit 2 are profound and you need to understand the way Retrofit two handles file uploads.
Before we dive deeper into the file upload topic with Retrofit two, permit's shortly 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 ii. Further, Retrofit 2 now leverages the OkHttp library for whatsoever network functioning and, as a result, OkHttp's classes for use cases like file uploads.
Using Retrofit 2, you need to use either OkHttp's RequestBody or MultipartBody.Part classes and encapsulate your file into a asking trunk. Let's take a look at the interface definition for file uploads.
public interface FileUploadService { @Multipart @POST("upload") Call<ResponseBody> upload( @Office("clarification") RequestBody clarification, @Part MultipartBody.Part file ); } Allow me explain each part of the definition in a higher place. Offset, you need to declare the entire call as @Multipart request. Let's go along with the annotation for description. The clarification is just a cord value wrapped within a RequestBody instance. Secondly, in that location'due south another @Part within the request: the actual file. We utilise the MultipartBody.Part class that allows us to ship the actual file proper name as well the binary file information with the request. You lot'll encounter how to create the file object correctly within the following section.
Android Client Lawmaking
At this signal, you lot've defined the necessary service interface for Retrofit. Now you tin move on and touch the actual file upload. We'll use the ServiceGenerator class which generates a service client. We've introduced the ServiceGenerator class in the creating a sustainable Android client tutorial earlier in this series.
The post-obit code 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, yous'll return within the onActivityResult() method of Android's lifecycle. In this method, you tin can become the file'due south uri and that's exactly what you'll utilize 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/blob/master/aFileChooser/src/com/ipaulpro/afilechooser/utils/FileUtils.java // 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 transport likewise the actual file name MultipartBody.Part trunk = MultipartBody.Office.createFormData("picture show", file.getName(), requestFile); // add some other part within the multipart request String descriptionString = "howdy, this is description speaking"; RequestBody description = RequestBody.create( okhttp3.MultipartBody.Course, descriptionString); // finally, execute the request Call<ResponseBody> 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 code to initialize the payload (body and description) and how to use the file upload service. As already mentioned, the RequestBody course is from OkHttp and used for the clarification. Its .create() method requires ii parameters: first, the media type, and 2d, the actual information. The media type for the description tin just be OkHttp's constant for multipart requests: okhttp3.MultipartBody.FORM. The media type for the file should ideally exist the actual content-type. For case, a PNG epitome should take image/png. Our lawmaking snippet above figures out the content blazon with the getContentResolver().getType(fileUri) call and and then parses the result into OkHttp's media blazon with MediaType.parse().
Besides the clarification, you'll add the file wrapped into a MultipartBody.Part instance. 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.
Remember the Content-Type
Please keep an eye on Retrofit's content blazon. If you intercept the underlying OkHttp client and change the content type to application/json, your server might accept issues with the deserialization process. Make sure yous're not defining the header indicating yous're sending JSON information, but multipart/class-data.
Next: Upload Files with Progress Updates
If you upload files in the foreground and they are not small, you might want to inform the user on your actions. Ideally, yous would display progress updates how much you've uploaded already. Nosotros've another tutorial on how to upload files with progress updates.
Exemplary Hapi Server for File Uploads
If yous already have your backend project, you can lean on the example lawmaking below. We use a simple hapi server with a POST route available at /upload. Additionally, we tell hapi to don't parse the incoming request, because we employ a Node.js library called multiparty for the payload parsing.
Inside the callback of multiparty's parsing function, we're logging each field to show its output.
method: 'POST', path: '/upload', config: { payload: { maxBytes: 209715200, output: 'stream', parse: false }, handler: function(request, respond) { var multiparty = crave('multiparty'); var form = new multiparty.Course(); form.parse(asking.payload, role(err, fields, files) { panel.log(err); console.log(fields); panel.log(files); return reply(util.inspect({fields: fields, files: files})); }); } } Android customer expects a return type of String, we're sending the received information as response. Of form your response will and should look dissimilar :)
Below you tin can see the output of a successful request and payload parsing on server-side. The commencement cipher is the err object. Afterwards, you can run into the fields which is merely the description as part of the request. And last but not to the lowest degree, the file is available within the pic field. Here y'all see our previously defined names on client side. 20160312_095248.jpg is passed equally the original name and the actual field name is picture. For further processing, access the uploaded image at path's location.
Server Log for Parsed Payload
null { description: [ 'how-do-you-do, 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 upwards-to-appointment apps and yous 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 expect within the next post on Retrofit? Next week you lot'll acquire all about how to get back logging inside Retrofit two. Stay tuned, it will be a good shot!
Source: https://futurestud.io/tutorials/retrofit-2-how-to-upload-files-to-server
Enregistrer un commentaire for "Galaxy File Upload Error File Size 0 Bytes"