Android Upload Image to Nodejs Server With Okhttp3
In this article, we will discuss the easiest mode 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 course, so you just demand to copy it in your project and it will do the rest.
one. Prerequisite
This article is specifically related to uploading files to the server when yous take its reference in the form of File, Uri, or Cord file path. Otherwise, if you don't have an thought of how to choice images, videos, files from the gallery, and documents. Or how to capture images, videos with a camera you can visit the following articles commencement according to your requirements.
1. Pick Image From Gallery in Kotlin – Android
ii. Capture Photo with Camera in Kotlin – Android
three. Pick Video From Gallery in Kotlin Android
4. Capture Video From Photographic camera in Kotlin Android
2. Dependency for OKHTTP3
Add together the following dependency in your projection level build.gradle file to import the OKHTTP3 library.
implementation("com.squareup.okhttp3:okhttp:four.7.2")
iii. 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 information technology at runtime to support Android API level 6.0 & above. For that purpose, we take already written this article Inquire 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 coffee.io.File class UploadUtility(activity: Activity) { var activity = activeness; var dialog: ProgressDialog? = zilch var serverURL: String = "https://handyopinion.com/tutorials/UploadToServer.php" var serverUploadDirectoryPath: String = "https://handyopinion.com/tutorials/uploads/" val client = OkHttpClient() fun uploadFile(sourceFilePath: Cord, uploadedFileName: String? = zilch) { uploadFile(File(sourceFilePath), uploadedFileName) } fun uploadFile(sourceFileUri: Uri, uploadedFileName: Cord? = naught) { val pathFromUri = URIPathHelper().getPath(action,sourceFileUri) uploadFile(File(pathFromUri), uploadedFileName) } fun uploadFile(sourceFile: File, uploadedFileName: String? = null) { Thread { val mimeType = getMimeType(sourceFile); if (mimeType == cypher) { Log.e("file mistake", "Non able to get mime type") render@Thread } val fileName: Cord = if (uploadedFileName == nix) sourceFile.proper name else uploadedFileName toggleProgressDialog(true) try { val requestBody: RequestBody = MultipartBody.Architect().setType(MultipartBody.FORM) .addFormDataPart("uploaded_file", fileName,sourceFile.asRequestBody(mimeType.toMediaTypeOrNull())) .build() val request: Request = Request.Architect().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.due east("File upload", "failed") showToast("File uploading failed") } } catch (ex: Exception) { ex.printStackTrace() Log.due east("File upload", "failed") showToast("File uploading failed") } toggleProgressDialog(false) }.showtime() } // url = file path or whatever suitable URL you want. fun getMimeType(file: File): String? { var type: Cord? = cypher val extension = MimeTypeMap.getFileExtensionFromUrl(file.path) if (extension != null) { blazon = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension) } return blazon } fun showToast(message: String) { activity.runOnUiThread { Toast.makeText( activeness, message, Toast.LENGTH_LONG ).evidence() } } fun toggleProgressDialog(show: Boolean) { activity.runOnUiThread { if (evidence) { dialog = ProgressDialog.show(activity, "", "Uploading file...", true); } else { dialog?.dismiss(); } } } }
In the above lawmaking, 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 lot already have a File reference you can remove this overloaded method. Otherwise copy URIPathHelper utility class from the post-obit link.
Get Path From URI In Kotlin Android
5. How to Use UploadUtility Form
As you can see in the UploadUtility course we have iii overloaded methods named uploadFile(...)
. Ane of them takes file String path every bit a parameter, one takes Uri reference and 3rd one takes File object as a parameter. If means yous can call whatever 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 yous can pass it. Otherwise, by default it will use the local file proper name on the server.
UploadUtility(this).uploadFile(YOUR_FILE_REFERENCE_OBJECT) // Either Uri, File or String file path
vi. 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 together the following lawmaking in that file.
<?php $file_path = "uploads/"; if(!is_dir($file_path)){ //Directory does not be, so lets create it. mkdir($file_path, 0755, true); } $file_path = $file_path . basename( $_FILES['uploaded_file']['proper name']); if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $file_path)) { repeat "success"; } else{ echo "neglect"; } ?>
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:
Transport Data to Server Using Google Volley in Android
Source: https://handyopinion.com/upload-file-to-server-in-android-kotlin/
0 Response to "Android Upload Image to Nodejs Server With Okhttp3"
Post a Comment