Showing posts with label android Image Upload using retrofit. Show all posts

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.