Hello friends, In this post, I will show you how to upload Image/Video/Any Files to the Server in Android using Retrofit 2. In Retrofit 2...

Upload File to Server using Retrofit in Android Upload File to Server using Retrofit in Android

Upload File to Server using Retrofit in Android

Upload File to Server using Retrofit in Android

Upload file using Retrofit
Hello friends, In this post, I will show you how to upload Image/Video/Any Files to the Server in Android using Retrofit 2. In Retrofit 2 Image or any type of files will be uploaded as Multipart. The File is received using php.

This Code is Updated with Multiple File Upload.

Upload Single File

Web Part:

Create a PHP file named as upload_image.php and paste the following lines.
<?php
$target_dir = "uploads/";
$target_file_name = $target_dir .basename($_FILES["file"]["name"]);
$response = array();

// Check if image file is a actual image or fake image
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 = false;
      $message = "Required Field Missing";
}
$response["success"] = $success;
$response["message"] = $message;
echo json_encode($response);

?>

Project Structure

Create a new Project in Android Studio with the required Specifications.

Codes:

AndroidManifest.xml
Don't forget to add the following permission in your manifest file
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
build.gradle
Open your app level build.gradle file add the following lines.
dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.3.0' 
    // dependency for Retrofit 2
    compile 'com.squareup.retrofit2:retrofit:2.0.0'
    compile 'com.squareup.retrofit2:converter-gson:2.0.0'
}
AppConfig.java
Create AppConfig.java and replace it with the following lines
class AppConfig {

    private static String BASE_URL = "http://mushtaq.16mb.com/";
    static Retrofit getRetrofit() {
        return new Retrofit.Builder()
                .baseUrl(AppConfig.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }
}
ApiConfig.java
Create ApiConfig.java and replace it with the following lines
interface ApiConfig {
    @Multipart
    @POST("retrofit_example/upload_image.php")
    Call uploadFile(@Part MultipartBody.Part file, @Part("file") RequestBody name);
}
ServerResponse.java
Create ServerResponse.java and replace it with the following lines. The Data Names are same as the Names in PHP(for example success and message)
class ServerResponse {

    // variable name should be same as in the json response from php
    @SerializedName("success")
    boolean success;
    @SerializedName("message")
    String message;

    String getMessage() {
        return message;
    }

    boolean getSuccess() {
        return success;
    }

}
activity_main.xml
Create activity_main.xml and Paste the following lines
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:scrollbars="none"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        tools:context=".MainActivity">

        <ImageView
            android:id="@+id/preview"
            android:layout_width="match_parent"
            android:layout_height="300dp"
            android:scaleType="centerCrop"
            android:src="@drawable/placeholder" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:orientation="horizontal">

            <Button
                android:id="@+id/pick_img"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="Pick Image" />

            <Button
                android:id="@+id/pick_vdo"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_gravity="center_horizontal"
                android:layout_weight="1"
                android:text="Pick Video" />

        </LinearLayout>

        <Button
            android:id="@+id/upload"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Upload" />

        <TextView
            android:id="@+id/filename1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:padding="5dp"
            android:text="FileName 1: " />

        <TextView
            android:id="@+id/filename2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:padding="5dp"
            android:text="FileName 2: " />

        <Button
            android:id="@+id/uploadMultiple"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Upload Multiple" />
    </LinearLayout>
</ScrollView>

Function to upload file:

// Uploading Image/Video
private void uploadFile() {
    progressDialog.show();

    // Map is used to multipart the file using okhttp3.RequestBody    File file = new File(mediaPath);

    // Parsing any Media type file    RequestBody requestBody = RequestBody.create(MediaType.parse("*/*"), file);
    MultipartBody.Part fileToUpload = MultipartBody.Part.createFormData("file", file.getName(), requestBody);
    RequestBody filename = RequestBody.create(MediaType.parse("text/plain"), file.getName());

    ApiConfig getResponse = AppConfig.getRetrofit().create(ApiConfig.class);
    Call call = getResponse.uploadFile(fileToUpload, filename);
    call.enqueue(new Callback() {
    @Override        
    public void onResponse(Call call, Response response) {
            ServerResponse serverResponse = response.body();
            if (serverResponse != null) {
                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 != null;
                Log.v("Response", serverResponse.toString());
            }
            progressDialog.dismiss();
        }

        @Override        
        public void onFailure(Call call, Throwable t) {

        }
    });
}

Upload Multiple Files

To Upload Multiple files, I made some changes as in the following.
Create a PHP file named as upload_multiple_files.php and paste the following lines.
<?php
 
$target_dir = "uploads/";
$target_file_name1 = $target_dir.basename($_FILES["file1"]["name"]);
$target_file_name2 = $target_dir.basename($_FILES["file2"]["name"]);
$response = array();

// Check if image file is a actual image or fake image
if (isset($_FILES["file1"])&&isset($_FILES["file2"])) 
{
 if (move_uploaded_file($_FILES["file1"]["tmp_name"], $target_file_name1)
  && move_uploaded_file($_FILES["file2"]["tmp_name"], $target_file_name2)) 
 {
  $success = true;
  $message = "Successfully Uploaded";
 }
 else 
 {
  $success = false;
  $message = "Error while uploading";
 }
}
else 
{
 $success = false;
 $message = "Required Field Missing";
}

$response["success"] = $success;
$response["message"] = $message;
echo json_encode($response);

?>

Function to upload multiple file:

Add the following code to upload multiple files in your activity/fragment
// Uploading Image/Video
 private void uploadMultipleFiles() {
        progressDialog.show();

        // Map is used to multipart the file using okhttp3.RequestBody
        File file = new File(mediaPath);
        File file1 = new File(mediaPath1);

        // Parsing any Media type file
        RequestBody requestBody1 = RequestBody.create(MediaType.parse("*/*"), file);
        RequestBody requestBody2 = RequestBody.create(MediaType.parse("*/*"), file1);

        MultipartBody.Part fileToUpload1 = MultipartBody.Part.createFormData("file1", file.getName(), requestBody1);
        MultipartBody.Part fileToUpload2 = MultipartBody.Part.createFormData("file2", file1.getName(), requestBody2);

        ApiConfig getResponse = AppConfig.getRetrofit().create(ApiConfig.class);
        Call<serverresponse> call = getResponse.uploadMulFile(fileToUpload1, fileToUpload2);
        call.enqueue(new Callback<serverresponse>() {
            @Override
            public void onResponse(Call<serverresponse> call, Response<serverresponse> response) {
                ServerResponse serverResponse = response.body();
                if (serverResponse != null) {
                    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 != null;
                    Log.v("Response", serverResponse.toString());
                }
                progressDialog.dismiss();
            }

            @Override
            public void onFailure(Call<serverresponse> call, Throwable t) {

            }
        });
    }
ApiConfig.java
Add the following interface for uploading multiple files in ApiConfig.java
@Multipart
@POST("retrofit_example/upload_multiple_files.php")
Call <serverresponse> uploadMulFile(@Part MultipartBody.Part file1, @Part MultipartBody.Part file2);

Full Source Code

Create MainActivity.java and Paste the following lines
This Code is Updated with Multiple File Upload.
public class MainActivity extends AppCompatActivity {

    Button btnUpload, btnMulUpload, btnPickImage, btnPickVideo;
    String mediaPath, mediaPath1;
    ImageView imgView;
    String[] mediaColumns = {MediaStore.Video.Media._ID};
    ProgressDialog progressDialog;
    TextView str1, str2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("Uploading...");

        btnUpload = (Button) findViewById(R.id.upload);
        btnMulUpload = (Button) findViewById(R.id.uploadMultiple);
        btnPickImage = (Button) findViewById(R.id.pick_img);
        btnPickVideo = (Button) findViewById(R.id.pick_vdo);
        imgView = (ImageView) findViewById(R.id.preview);
        str1 = (TextView) findViewById(R.id.filename1);
        str2 = (TextView) findViewById(R.id.filename2);

        btnUpload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                uploadFile();
            }
        });

        btnMulUpload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                uploadMultipleFiles();
            }
        });

        btnPickImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent galleryIntent = new Intent(Intent.ACTION_PICK,
                        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(galleryIntent, 0);
            }
        });

        // Video must be low in Memory or need to be compressed before uploading...
        btnPickVideo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent galleryIntent = new Intent(Intent.ACTION_PICK,
                        android.provider.MediaStore.Video.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(galleryIntent, 1);
            }
        });

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        try {
            // When an Image is picked
            if (requestCode == 0 && resultCode == RESULT_OK && null != data) {

                // Get the Image from data
                Uri selectedImage = data.getData();
                String[] filePathColumn = {MediaStore.Images.Media.DATA};

                Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
                assert cursor != null;
                cursor.moveToFirst();

                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                mediaPath = cursor.getString(columnIndex);
                str1.setText(mediaPath);
                // Set the Image in ImageView for Previewing the Media
                imgView.setImageBitmap(BitmapFactory.decodeFile(mediaPath));
                cursor.close();

            } // When an Video is picked
            else if (requestCode == 1 && resultCode == RESULT_OK && null != data) {

                // Get the Video from data
                Uri selectedVideo = data.getData();
                String[] filePathColumn = {MediaStore.Video.Media.DATA};

                Cursor cursor = getContentResolver().query(selectedVideo, filePathColumn, null, null, null);
                assert cursor != null;
                cursor.moveToFirst();

                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);

                mediaPath1 = cursor.getString(columnIndex);
                str2.setText(mediaPath1);
                // Set the Video Thumb in ImageView Previewing the Media
                imgView.setImageBitmap(getThumbnailPathForLocalFile(MainActivity.this, selectedVideo));
                cursor.close();

            } else {
                Toast.makeText(this, "You haven't picked Image/Video", Toast.LENGTH_LONG).show();
            }
        } catch (Exception e) {
            Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG).show();
        }

    }

    // Providing Thumbnail For Selected Image
    public Bitmap getThumbnailPathForLocalFile(Activity context, Uri fileUri) {
        long fileId = getFileId(context, fileUri);
        return MediaStore.Video.Thumbnails.getThumbnail(context.getContentResolver(),
                fileId, MediaStore.Video.Thumbnails.MICRO_KIND, null);
    }

    // Getting Selected File ID
    public long getFileId(Activity context, Uri fileUri) {
        Cursor cursor = context.managedQuery(fileUri, mediaColumns, null, null, null);
        if (cursor.moveToFirst()) {
            int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Video.Media._ID);
            return cursor.getInt(columnIndex);
        }
        return 0;
    }

    // Uploading Image/Video
    private void uploadFile() {
        progressDialog.show();

        // Map is used to multipart the file using okhttp3.RequestBody
        File file = new File(mediaPath);

        // Parsing any Media type file
        RequestBody requestBody = RequestBody.create(MediaType.parse("*/*"), file);
        MultipartBody.Part fileToUpload = MultipartBody.Part.createFormData("file", file.getName(), requestBody);
        RequestBody filename = RequestBody.create(MediaType.parse("text/plain"), file.getName());

        ApiConfig getResponse = AppConfig.getRetrofit().create(ApiConfig.class);
        Call<serverresponse> call = getResponse.uploadFile(fileToUpload, filename);
        call.enqueue(new Callback<serverresponse>() {
            @Override
            public void onResponse(Call<serverresponse> call, Response<serverresponse> response) {
                ServerResponse serverResponse = response.body();
                if (serverResponse != null) {
                    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 != null;
                    Log.v("Response", serverResponse.toString());
                }
                progressDialog.dismiss();
            }

            @Override
            public void onFailure(Call<serverresponse> call, Throwable t) {

            }
        });
    }

    // Uploading Image/Video
    private void uploadMultipleFiles() {
        progressDialog.show();

        // Map is used to multipart the file using okhttp3.RequestBody
        File file = new File(mediaPath);
        File file1 = new File(mediaPath1);

        // Parsing any Media type file
        RequestBody requestBody1 = RequestBody.create(MediaType.parse("*/*"), file);
        RequestBody requestBody2 = RequestBody.create(MediaType.parse("*/*"), file1);

        MultipartBody.Part fileToUpload1 = MultipartBody.Part.createFormData("file1", file.getName(), requestBody1);
        MultipartBody.Part fileToUpload2 = MultipartBody.Part.createFormData("file2", file1.getName(), requestBody2);

        ApiConfig getResponse = AppConfig.getRetrofit().create(ApiConfig.class);
        Call<serverresponse> call = getResponse.uploadMulFile(fileToUpload1, fileToUpload2);
        call.enqueue(new Callback() {
            @Override
            public void onResponse(Call<serverresponse> call, Response<serverresponse> response) {
                ServerResponse serverResponse = response.body();
                if (serverResponse != null) {
                    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 != null;
                    Log.v("Response", serverResponse.toString());
                }
                progressDialog.dismiss();
            }

            @Override
            public void onFailure(Call<serverresponse> call, Throwable t) {

            }
        });
    }

}

Download Code:

You can download the full source from the following Github link. If you Like this tutorial, Please star it in Github.
    
Download From Github

Post your doubts and comments in the comments section.  

30 comments:

  1. NOT WORKING-WHENEVER I SELECT VIDEO IT SHOWS SOMTHING WENT WRONG,AND WHENEVER SELECT IMAGE IT DOES NOT SELECT IMAGE BUT DOES NOT VIEW IN IMAGE VIEW AND WHEN I PRESS UPLOAD BUTTON IT JUST SHOWS PROGRESS NOTHING ELSE

    ReplyDelete
  2. NOW THIS NEW ERROR
    08-11 11:20:50.284 18045-18045/com.saeed.lastretrofitvideo V/ActivityThread: updateVisibility : ActivityRecord{747ddb5 token=android.os.BinderProxy@9333a3e {com.saeed.lastretrofitvideo/com.saeed.lastretrofitvideo.MainActivity}} show : false

    ReplyDelete
    Replies
    1. Hi plz follow the proper scenario. This wont work. Its just a basic things

      Delete
    2. Hi Saeed,
      It is worked for me perfectly

      Delete
  3. It happens because of Timeout in Server

    ReplyDelete
  4. I tried your code. But actually it does not reach upto php file. and response will be null. what to do now?

    ReplyDelete
  5. Replies
    1. Possible But timeout may happen due to its size

      Delete
  6. Hello its nice Tutorial.

    Can you show me the exact url which you are using in this example

    ReplyDelete
  7. I Already Provided the PHP File above

    ReplyDelete
    Replies
    1. Is this php file work.... Its not proper guide mustaq. Plz update this. Not having basic structure of the php

      Delete
  8. Please provide code upload all type of files.

    ReplyDelete
    Replies
    1. If u want convert all files plz encode the file based on its type. Refer how to encode the file type. U need to handle time out exception also which provided by google.

      Delete
  9. how can i pass other params like email,bday etc in this example.

    ReplyDelete
  10. Veryy GOOD :)))
    Thankss
    How multiple images

    ReplyDelete
    Replies
    1. Thanks Bro, for your support.
      I updated the post with Multiple File Upload using Retrofit
      Link to Upload Multiple Files

      Delete
  11. How can the progress of the upload be shown in percentage? Your code worked.

    ReplyDelete
  12. hi good script work perfect thx

    but now i need to pass an extra parameter for sub directory

    uploads/"extra parameter"/filename

    how can i do this

    ReplyDelete
  13. Great awesome tutorial !
    I have run itu successfully, if I wanna upload with mysql query, which code is must replace in php file or android class?

    ReplyDelete
  14. Thank You, its great, everything works well, but how can I change source directory (for example Environment.getExternalStorageDirectory() + "/some_dir/"), when I want to upload *.txt files...? Thanks, Ivo

    ReplyDelete
  15. Its not working for the video any soln

    ReplyDelete
  16. video upload not working bro

    ReplyDelete
  17. Wow! Such an amazing and helpful post this is. I really really love it. It's so good and so awesome. I am just amazed.
    split pdf into multiple files online

    ReplyDelete
  18. Incredible new multicam support. Ground-breaking keying highlights. Supports Thunderbolt and studio-screen yield.
    AnyConv

    ReplyDelete
  19. Visual depiction is a quickly developing industry that requires a great deal of aptitudes from workers. Professional graphic design

    ReplyDelete
  20. It is showing Error while uploading

    ReplyDelete

Please Comment about the Posts and Blog