Upload Image or File to Server in Android Kotlin

In this article, we will discuss the easiest way to upload all types of files, images, videos, pdf, and all other to the server in Android using Kotlin. We are going to upload file to Server in Android Kotlin using OKHTTP multipart request. In the following, the code is shared in the form of Utility class, so you just need to copy it in your project and it will do the rest.

Upload File to Server in Android

1. Prerequisite

This article is specifically related to uploading files to the server when you have its reference in the form of File, Uri, or String file path. Otherwise, if you don’t have an idea of how to pick images, videos, files from the gallery, and documents. Or how to capture images, videos with a camera you can visit the following articles first according to your requirements.

1. Pick Image From Gallery in Kotlin – Android
2. Capture Photo with Camera in Kotlin – Android
3. Pick Video From Gallery in Kotlin Android
4. Capture Video From Camera in Kotlin Android

2. Dependency for OKHTTP3

Add the following dependency in your project level build.gradle file to import the OKHTTP3 library.

implementation("com.squareup.okhttp3:okhttp:4.7.2")

3. Required Permissions to Access Files for Uploading

We need READ_EXTERNAL_STORAGE permission to access device storage to access files, images, and videos. For that purpose add the following permission in your AndroidManifest.xml file above the application tag.

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

This READ_EXTERNAL_STORAGE permission is dangerous permission. That means we need to handle it at runtime to support Android API level 6.0 & above. For that purpose, we have already written this article Ask Runtime Permission in Kotlin Android.

4. Independent Utility Class to Upload File to Server in Android Kotlin

Create a new file in your project with the name UploadUtility.kt and paste the following class code in it.

package com.mvp.handyopinion

import android.app.Activity
import android.app.ProgressDialog
import android.net.Uri
import android.util.Log
import android.webkit.MimeTypeMap
import android.widget.Toast
import okhttp3.*
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody.Companion.asRequestBody
import java.io.File

class UploadUtility(activity: Activity) {

    var activity = activity;
    var dialog: ProgressDialog? = null
    var serverURL: String = "https://handyopinion.com/tutorials/UploadToServer.php"
    var serverUploadDirectoryPath: String = "https://handyopinion.com/tutorials/uploads/"
    val client = OkHttpClient()

    fun uploadFile(sourceFilePath: String, uploadedFileName: String? = null) {
        uploadFile(File(sourceFilePath), uploadedFileName)
    }

    fun uploadFile(sourceFileUri: Uri, uploadedFileName: String? = null) {
        val pathFromUri = URIPathHelper().getPath(activity,sourceFileUri)
        uploadFile(File(pathFromUri), uploadedFileName)
    }

    fun uploadFile(sourceFile: File, uploadedFileName: String? = null) {
        Thread {
            val mimeType = getMimeType(sourceFile);
            if (mimeType == null) {
                Log.e("file error", "Not able to get mime type")
                return@Thread
            }
            val fileName: String = if (uploadedFileName == null)  sourceFile.name else uploadedFileName
            toggleProgressDialog(true)
            try {
                val requestBody: RequestBody =
                    MultipartBody.Builder().setType(MultipartBody.FORM)
                        .addFormDataPart("uploaded_file", fileName,sourceFile.asRequestBody(mimeType.toMediaTypeOrNull()))
                        .build()

                val request: Request = Request.Builder().url(serverURL).post(requestBody).build()

                val response: Response = client.newCall(request).execute()

                if (response.isSuccessful) {
                    Log.d("File upload","success, path: $serverUploadDirectoryPath$fileName")
                    showToast("File uploaded successfully at $serverUploadDirectoryPath$fileName")
                } else {
                    Log.e("File upload", "failed")
                    showToast("File uploading failed")
                }
            } catch (ex: Exception) {
                ex.printStackTrace()
                Log.e("File upload", "failed")
                showToast("File uploading failed")
            }
            toggleProgressDialog(false)
        }.start()
    }

    // url = file path or whatever suitable URL you want.
    fun getMimeType(file: File): String? {
        var type: String? = null
        val extension = MimeTypeMap.getFileExtensionFromUrl(file.path)
        if (extension != null) {
            type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension)
        }
        return type
    }

    fun showToast(message: String) {
        activity.runOnUiThread {
            Toast.makeText( activity, message, Toast.LENGTH_LONG ).show()
        }
    }

    fun toggleProgressDialog(show: Boolean) {
        activity.runOnUiThread {
            if (show) {
                dialog = ProgressDialog.show(activity, "", "Uploading file...", true);
            } else {
                dialog?.dismiss();
            }
        }
    }

}

In the above code, you will see one syntax Error at the line URIPathHelper().getPath. This is used to convert your Uri object into the File object. But if you already have a File reference you can remove this overloaded method. Otherwise copy URIPathHelper utility class from the following link.

Get Path From URI In Kotlin Android

5. How to Use UploadUtility Class

As you can see in the UploadUtility class we have 3 overloaded methods named uploadFile(...). One of them takes file String path as a parameter, one takes Uri reference and 3rd one takes File object as a parameter. If means you can call any of them depending upon your file reference as shown in the following code. But before that also have a loot at the second parameter named uploadedFileName in all of these overloaded methods. It’s an optional parameter. If you want to save the file on the server with some specific file name you can pass it. Otherwise, by default it will use the local file name on the server.

UploadUtility(this).uploadFile(YOUR_FILE_REFERENCE_OBJECT) // Either Uri, File or String file path

6. Server side PHP Script

In this article, we are going to upload files to the PHP server for that create a PHP file on your server and add the following code in that file.

<?php
  
    $file_path = "uploads/";
    if(!is_dir($file_path)){
        //Directory does not exist, so lets create it.
        mkdir($file_path, 0755, true);
    }
    
    $file_path = $file_path . basename( $_FILES['uploaded_file']['name']);
    if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $file_path)) {
        echo "success";
    } else{
        echo "fail";
    }
 ?>

Don’t forget to change your server URL in the above Kotlin UploadUtility class.

That’s it. Enjoy 🙂

Please don’t hesitate to ask your questions or give suggestions in the comments section below.

Next:

Send Data to Server Using Google Volley in Android

Please share this post:
Native Mobile Application Developer (Android + IOS) having experience in Java, Swift, Kotlin, Objective C, Unity, C#, C/C++, NODE JS & PHP.

Ask a Question

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Related Posts

Begin typing your search term above and press enter to search. Press ESC to cancel.

%d bloggers like this: