Home » How to Easily Upload Image to the server Programmatically in Android
Upload Image to Server Android

How to Easily Upload Image to the server Programmatically in Android

Reading time: 14 Minutes

This post explains how to upload images easily to the server host in Android in simple steps.

  1.  Create an new Android project or Go to your Android Project in Android Studio.
  2. Describe & Ask User Permissions for  External Storage and Internet Usage in AndroidManifest.xml File.
  3. Create an Helper Class to handle the Http Server Requests for posting the image in Server.
  4. Create UI elements like Buttons, WebView to support the project .
  5. Create Backend PHP files to upload Image in Server directory.
  6. Create an Background Async task for handle the Server Request & Response .

Lets see these steps in detail.

Step 1 (Creating Android Project) :

Go to File -> New -> New Project , Select Empty Activity & click Next to Proceed

Create New Android Project 1

Configure Your Project Dialog Appears.

Provide your Project Name, Package, Choose Language to Java & click Finish. Your Project will start Building automatically.

Step 2 (User Permissios in AndroidManifest .xml File) :

Add 

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

       in Manifest File to request  Permission & also Don’t forget to ask permission @ runtime to program for the latest devices.

AndroidManifest.xml


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.atooz.learning">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.Learning">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>

</manifest>

Step 3 (Helper Class to Handle Http Request ) :

Create a Java Class

HttpRequestHelper

  in java/com.androidkk.learning Folder & write the following code.

package com.androidkk.learning;

import android.graphics.Bitmap;
import android.util.Log;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpRequestHelper {
private HttpURLConnection httpConn;
private DataOutputStream request;
private final String boundary = "*****";
private final String crlf = "\r\n";
private final String twoHyphens = "--";

public HttpRequestHelper(String requestURL){
try {
// creates a unique boundary based on time stamp
URL url = new URL(requestURL);
httpConn = (HttpURLConnection) url.openConnection();
httpConn.setUseCaches(false);
httpConn.setDoOutput(true);
httpConn.setDoInput(true);

httpConn.setRequestMethod("POST");
httpConn.setRequestProperty("Connection", "Keep-Alive");
httpConn.setRequestProperty("Cache-Control", "no-cache");
httpConn.setRequestProperty(
"Content-Type", "multipart/form-data;boundary=" + this.boundary);

request = new DataOutputStream(httpConn.getOutputStream());
}catch (Exception e){
Log.e("Exception",e.toString());
}
}

public void addFormField(String name, String value) {
try {
request.writeBytes(this.twoHyphens + this.boundary + this.crlf);
request.writeBytes("Content-Disposition: form-data; name=\"" + name + "\"" + this.crlf);
request.writeBytes("Content-Type: text/plain; charset=UTF-8" + this.crlf);
request.writeBytes(this.crlf);
request.writeBytes(value + this.crlf);
request.flush();
}
catch (Exception e){
Log.e(getClass()+"Exception",e.toString());
}
}

public void addFilePart(String fieldName, Bitmap inImage)
{
try {
String fileName = "temporary.jpg";
request.writeBytes(this.twoHyphens + this.boundary + this.crlf);
request.writeBytes("Content-Disposition: form-data; name=\"" +
fieldName + "\";filename=\"" +
fileName + "\"" + this.crlf);
request.writeBytes(this.crlf);
ByteArrayOutputStream bytes1 = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes1);
byte[] bytes = bytes1.toByteArray();
request.write(bytes);
}
catch (Exception e){
Log.e(getClass()+"Exception",e.toString());
}
}

public String finish() {
String response = "";
try {
request.writeBytes(this.crlf);
request.writeBytes(this.twoHyphens + this.boundary +
this.twoHyphens + this.crlf);
request.flush();
request.close();
int status = httpConn.getResponseCode();
if (status == HttpURLConnection.HTTP_OK) {
InputStream responseStream = new
BufferedInputStream(httpConn.getInputStream());
BufferedReader responseStreamReader =
new BufferedReader(new InputStreamReader(responseStream));

String line = "";
StringBuilder stringBuilder = new StringBuilder();
while ((line = responseStreamReader.readLine()) != null) {
stringBuilder.append(line).append("\n");
}
responseStreamReader.close();
response = stringBuilder.toString().trim();
httpConn.disconnect();
} else {
throw new IOException("Server returned non-OK status: " + status);
}
}
catch(Exception e){
Log.e(getClass()+"Exception",e.toString());
}
return response;
}

}

Step 4 (UI elements to support the Project) :

Go to activity_main.xml layout file.

Create Button for Upload Image & Webview to view the uploaded image from Server using link .

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Upload Images"
android:layout_gravity="center"
android:id="@+id/upladImageBtn"
android:layout_margin="20dp"/>

<WebView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="20dp"
android:id="@+id/uploadedWebView"/>

</LinearLayout>

Step 5 (Backend PHP files for handling Upload in Server Side) :

Create uploadImage.php  in Server Host & Write the backend Handler Code for Uploading :

uploadImage.php

<?php

$target_dir = "uploads/";
if(!is_dir($target_dir)) {
mkdir($target_dir);
}

$target_file = $target_dir . basename($_FILES["image_name"]["name"]);


if (move_uploaded_file($_FILES["image_name"]["tmp_name"], $target_file)) {
echo $target_file;
} else {
echo "0";
}
?>

Step 6 (Last Step in MainActivity) :

  • Initialize uploadImage Button & call Image Chooser Gallery Intent on uploadImage Button click.
  • Get Result from Image Chooser Gallery Intent on onActivityResult method.
  • Create a AsyncTask Class inside MainActivity & pass the Intent Data to that Class to handle the  Background operations (Web Request).
  • Do the Web Request & Response Activities in doInBackground Method & return to onPostExecute method to execute the UI updations (Loading Image From Server in WebView) .

MainActivity.java

package com.androidkk.learning;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager2.widget.ViewPager2;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import com.androidkk.learning.helper.Tab1;
import com.androidkk.learning.helper.Tab2;
import com.androidkk.learning.helper.TabFragmentAdapter;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;

public class MainActivity extends AppCompatActivity {

//String tabName[] = new String[]{"Tab 1","Tab 2"};

private static final int SELECT_IMAGE_REQUEST_CODE = 100;

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

}

public void init(){
Button uploadImgBtn = (Button) findViewById(R.id.upladImageBtn);
uploadImgBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
imageChooserIntent();
}
});
}

public void imageChooserIntent(){
Intent intent = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

intent.setType("image/*");
startActivityForResult(
Intent.createChooser(intent, "Select File"),
SELECT_IMAGE_REQUEST_CODE);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);

switch (requestCode){
case SELECT_IMAGE_REQUEST_CODE:
if (resultCode == Activity.RESULT_OK) {
Uri selectedImageUri = data.getData();
String tempPath = getPath(selectedImageUri, this);
Bitmap bm;
BitmapFactory.Options btmapOptions = new BitmapFactory.Options();
btmapOptions.inSampleSize = 2;
bm = BitmapFactory.decodeFile(tempPath, btmapOptions);
//Toast.makeText(this, tempPath, Toast.LENGTH_SHORT).show();
//mImageView.setImageBitmap(bm);
UploadImageToServer uploadImageToServer = new UploadImageToServer("http://192.168.43.176/androidKK_Projects/uploadImage.php",bm);
uploadImageToServer.execute();

}
break;
}


}

public String getPath(Uri uri, Activity activity) {
String[] projection = {MediaStore.MediaColumns.DATA};
Cursor cursor = activity
.managedQuery(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}

private class UploadImageToServer extends AsyncTask<String, String, String>{
String requesturl = "";
Bitmap bitmap = null;
UploadImageToServer(String requestUrl, Bitmap bitmap){
this.requesturl = requestUrl;
this.bitmap = bitmap;
}

@Override
protected String doInBackground(String... strings) {
if(!this.requesturl.equals("")){
HttpRequestHelper httpRequestHelper = new HttpRequestHelper(requesturl);
httpRequestHelper.addFilePart("image_name", bitmap);
String response = httpRequestHelper.finish();
return response;
}
return "";
}


@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Log.e("Result" , result);
if(!result.equals("0")){

WebView uploadedImageView = (WebView) findViewById(R.id.uploadedWebView);
uploadedImageView.loadUrl("http://192.168.43.176/androidKK_Projects/"+result);
Toast.makeText(MainActivity.this, "Image is uploaded", Toast.LENGTH_SHORT).show();

}else{
//Toast.makeText(MainActivity.this, "Image is not uploaded", Toast.LENGTH_SHORT).show();
}
}
}

}
Upload Image to Server Android

 

That’s all. We have Built an Sample Android App for Uploading Image into Server using Java . Happy Programming. Thanks.

Related Posts

Leave a Reply

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

%d bloggers like this: