Code Example

Android OkHttp Multipart Upload Image Snippets

Learn about how to implement a multipart image upload in OkHttp in android via simple code snippets and examples.

1. Android Multipart OkHttp Upload drawable

A simple step by step Android OkHttp Multipart uploading of a drawable image asynchronously example.

This is a Simple Android Application for multipart file uploading using OkHttp (async way).

Here is the code snippet of getting the drawable, compressing it as a bitmap and uploading it to the server using OkHttp:

        Drawable drawable = ContextCompat.getDrawable(mContext, R.drawable.ic_launcher);
        if (drawable != null) {
            Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.PNG, 0, stream);
            final byte[] bitmapdata = stream.toByteArray();

            OkHttpClient client = new OkHttpClient();
            RequestBody requestBody = new MultipartBuilder()
                    .type(MultipartBuilder.FORM)
                    .addPart(
                            Headers.of("Content-Disposition", "form-data; name="file"; filename="ic_launcher.png""),
                            RequestBody.create(MEDIA_TYPE_PNG, bitmapdata))
                    .build();
            final Request request = new Request.Builder()
                    .url("http://192.168.1.100:20583/fileupload")
                    .post(requestBody)
                    .build();

            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(final Request request, final IOException e) {
                    Log.e(LOG_TAG, e.toString());
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(mContext, e.toString(), Toast.LENGTH_SHORT).show();
                            mTextView.setText(e.toString());
                        }
                    });
                }

                @Override
                public void onResponse(Response response) throws IOException {
                    final String message = response.toString();
                    Log.i(LOG_TAG, message);
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(mContext, message, Toast.LENGTH_SHORT).show();
                            mTextView.setText(message);
                        }
                    });
                }
            });
        }

This example will comprise the following files:

  • MainActivity.java

Step 1: Create Project

  1. Open your AndroidStudio IDE.
  2. Go to File-->New-->Project to create a new project.

Step 2: Dependencies

In your app/build.gradle add dependencies as shown below:

Add OkHttp as a dependency:

dependencies {
   //..
    implementation 'com.squareup.okhttp:okhttp:2.7.0'
}

Step 3: Design Layouts

*(a). activity_main.xml

Create a file named activity_main.xml and design it as follows:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.multipartokhttp.MainActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!" />
</RelativeLayout>

Step 4: Write Code

Write Code as follows:

(a). MainActivity.java

Create a file named MainActivity.java

Here is the full code

package com.example.multipartokhttp;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

import com.squareup.okhttp.Callback;
import com.squareup.okhttp.Headers;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.MultipartBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

public class MainActivity extends AppCompatActivity {
    private final Context mContext = this;
    private static final String LOG_TAG = "OkHttp";
    private TextView mTextView;
    private Handler mHandler;
    private static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");

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

        mTextView = (TextView) findViewById(R.id.textView);
        mHandler = new Handler(Looper.getMainLooper());

        // Multipart request, upload file...
        Drawable drawable = ContextCompat.getDrawable(mContext, R.drawable.ic_launcher);
        if (drawable != null) {
            Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.PNG, 0, stream);
            final byte[] bitmapdata = stream.toByteArray();

            OkHttpClient client = new OkHttpClient();
            RequestBody requestBody = new MultipartBuilder()
                    .type(MultipartBuilder.FORM)
                    .addPart(
                            Headers.of("Content-Disposition", "form-data; name="title""),
                            RequestBody.create(null, "Sample Text Content"))
                    .addPart(
                            Headers.of("Content-Disposition", "form-data; name="file"; filename="ic_launcher.png""),
                            RequestBody.create(MEDIA_TYPE_PNG, bitmapdata))
                    .build();
            final Request request = new Request.Builder()
                    .url("http://192.168.1.100:20583/fileupload")
                    .post(requestBody)
                    .build();

            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(final Request request, final IOException e) {
                    Log.e(LOG_TAG, e.toString());
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(mContext, e.toString(), Toast.LENGTH_SHORT).show();
                            mTextView.setText(e.toString());
                        }
                    });
                }

                @Override
                public void onResponse(Response response) throws IOException {
                    final String message = response.toString();
                    Log.i(LOG_TAG, message);
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(mContext, message, Toast.LENGTH_SHORT).show();
                            mTextView.setText(message);
                        }
                    });
                }
            });
        }
    }
}

Step 5: Add Permissions

Add the following two permissions in your AndroidManifest.xml:

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Run

Simply copy the source code into your Android Project,Build and Run.

Read More.