Using Post Retrofit to Upload File Android
-
- Updated date Feb 19, 2020
- 116.7k
- half dozen
In this article, we will learn how to upload any file to an online server using Retrofit 2 in Android.
Introduction
In this article, we will larn how to upload any file to an online server using Retrofit 2 in Android.
Retrofit
Retrofit is an awesome HTTP library that improves the speed of server calls improve than other HTTP libraries like Volley and Fast Android Networking. It depends on OKHTTP. To know more about the Retrofit visit here.
I accept used PHP every bit my backend to receive the uploaded files from the Android App to the server. The coding function is split into two as server-side & client-side.
Coding Part,
Server Side
- To use PHP, yous need PhpMyAdmin (with WAMP or XMPP) server.
- Then open your hosting path (For WAMP – C:\Wamp\www).
- Create a PHP file named equally PHP and paste the post-obit lines.
- <?php
- $target_dir ="uploads/" ;
- $target_file_name = $target_dir .basename($_FILES["file" ][ "proper name" ]);
- $response = assortment();
- if (isset($_FILES[ "file" ]))
- {
- if (move_uploaded_file($_FILES[ "file" ][ "tmp_name" ], $target_file_name))
- {
- $success =true ;
- $message ="Successfully Uploaded" ;
- }
- else
- {
- $success =false ;
- $message ="Error while uploading" ;
- }
- }
- else
- {
- $success =fake ;
- $message ="Required Field Missing" ;
- }
- $response["success" ] = $success;
- $response["message" ] = $bulletin;
- echo json_encode($response);
- ?>
- I have created a folder named "uploads" to maintain uploaded files.
Customer-Side
I accept carve up this part into 3 steps as in the following.
- Step 1 - Creating a New Project with Empty Activity.
- Step ii - Setting up the Retrofit HTTP Library and Manifest.
- Step 3 - Implementation of File uploader using Retrofit.
Step 1 - Creating a New Project with Android Studio
- Open Android Studio and Select Create a new projection.
- Proper noun the project as your wish and select your activeness template.
- Click the " Stop " push to create a new project in Android Studio.
Pace 2 - Setting upwards the Retrofit Http Library and Manifest
In this function, we will see how to prepare the library for the project.
- Then add the following lines in-app level build.gradle file to use Google services to your project.
- dependencies {
- ...
- implementation'com.squareup.retrofit2:retrofit:two.0.0'
- implementation'com.squareup.retrofit2:converter-gson:two.0.0'
- }
- Then click "Sync At present" to setup your project.
- Don't forget to add the following permission in your manifest file.
- <uses-permission android:proper noun= "android.permission.Internet" />
- <uses-permission android:proper name="android.permission.WRITE_EXTERNAL_STORAGE" />
Step iii - Implementation of File Uploader using Retrofit 2
- Create a grade file named as "AppConfig.coffee" and add the following lines.
- class AppConfig {
- private static Cord BASE_URL = "base_address" ;
- static Retrofit getRetrofit() {
- render new Retrofit.Builder()
- .baseUrl(AppConfig.BASE_URL)
- .addConverterFactory(GsonConverterFactory.create())
- .build();
- }
- }
- Create an interface file named as "ApiConfig.java" and add the following lines.
- interface ApiConfig {
- @Multipart
- @POST("retrofit_example/upload_image.php" )
- Phone call uploadFile(@Office MultipartBody.Part file, @Part("file" ) RequestBody proper name);
- }
- Create a model class named equally "ServerResponse.coffee" and add the following lines
- class ServerResponse {
- @SerializedName("success" )
- boolean success;
- @SerializedName("message" )
- String bulletin;
- Cord getMessage() {
- render bulletin;
- }
- boolean getSuccess() {
- return success;
- }
- }
- The SerializedName annotation is used to parsing the server response and their name & type should be the same as the JSON Response received from the server.
- The files are uploaded using MultipartBody of OkHttp3. The following code snippet is used to upload the file.
- private void uploadFile() {
- File file =new File(mediaPath);
- RequestBody requestBody = RequestBody.create(MediaType.parse("*/*" ), file);
- MultipartBody.Part fileToUpload = MultipartBody.Part.createFormData("file" , file.getName(), requestBody);
- RequestBody filename = RequestBody.create(MediaType.parse("text/manifestly" ), file.getName());
- ApiConfig getResponse = AppConfig.getRetrofit().create(ApiConfig.class );
- Phone call call = getResponse.uploadFile(fileToUpload, filename);
- call.enqueue(new Callback() {
- @Override
- public void onResponse(Call call, Response response) {
- ServerResponse serverResponse = response.body();
- if (serverResponse != nada ) {
- if (serverResponse.getSuccess()) {
- Toast.makeText(getApplicationContext(), serverResponse.getMessage(),Toast.LENGTH_SHORT).show();
- }else {
- Toast.makeText(getApplicationContext(), serverResponse.getMessage(),Toast.LENGTH_SHORT).show();
- }
- }else {
- assert serverResponse !=aught ;
- Log.v("Response" , serverResponse.toString());
- }
- progressDialog.dismiss();
- }
- @Override
- public void onFailure(Call phone call, Throwable t) {
- }
- });
- }
- Hither, Map is used to multipart the file using okhttp3.RequestBody.
- RequestBody is created with the selected file & MultipartBody. A office with file RequestBody.
- Nosotros can pass media files with a normal server call also.
In this office, we have learned how to upload a single file using Retrofit 2. IN the adjacent role we will learn how to upload multiple files using Retrofit two.
Download Code
Yous tin download the full source code of the commodity in GitHub. If y'all like this article, practice star the repo in GitHub.
highsmithapereens.blogspot.com
Source: https://www.c-sharpcorner.com/article/upload-files-to-server-using-retrofit-2-in-android/
0 Response to "Using Post Retrofit to Upload File Android"
Post a Comment