Hello guys, in this post I came up with an easy solution for uploading files from android to server. So today we will see an example of Android Upload Image to Server. I have already posted some example of Android Upload Image to Server previously. Â But in this post we will use android upload service for our Android Upload Image App.
Check the Updated Android Upload File Tutorial Here
In this tutorial I will store the image file inside servers directory and in database I will store the URL of the image. For this I will use Android Upload Service library and it makes uploading files super easy. So lets see how we can do it. First we will create our server side codes.
Android Upload Image to Server Video Tutorial
- You can also go through this video tutorial to learn how to upload image from android to server.
Creating Server Side Codes for Android Upload Image
The first thing we need is to create our server side web services. For server side I am using PHP and MySQL. And for this I am using Wamp server. You can still use xampp or any other application. Now follow the steps to create your web service to handle the file upload.
- Go to localhost/phpmyadmin and create the following database table.
- Now inside your server’s root directory (c:/wamp/www) and create a new folder. I created AndroidUploadImage.
- Inside the folder create a folder named uploads, in this folder we will save all the uploaded images.
- Create a file named dbDetails.php and write the following code.
1 2 3 4 5 6 7 |
<?php define('HOST','localhost'); define('USER','root'); define('PASS',''); define('DB','db_images'); |
- Now create a file named upload.php and write the following code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 |
<?php //importing dbDetails file require_once 'dbDetails.php'; //this is our upload folder $upload_path = 'uploads/'; //Getting the server ip $server_ip = gethostbyname(gethostname()); //creating the upload url $upload_url = 'http://'.$server_ip.'/AndroidImageUpload/'.$upload_path; //response array $response = array(); if($_SERVER['REQUEST_METHOD']=='POST'){ //checking the required parameters from the request if(isset($_POST['name']) and isset($_FILES['image']['name'])){ //connecting to the database $con = mysqli_connect(HOST,USER,PASS,DB) or die('Unable to Connect...'); //getting name from the request $name = $_POST['name']; //getting file info from the request $fileinfo = pathinfo($_FILES['image']['name']); //getting the file extension $extension = $fileinfo['extension']; //file url to store in the database $file_url = $upload_url . getFileName() . '.' . $extension; //file path to upload in the server $file_path = $upload_path . getFileName() . '.'. $extension; //trying to save the file in the directory try{ //saving the file move_uploaded_file($_FILES['image']['tmp_name'],$file_path); $sql = "INSERT INTO `db_images`.`images` (`id`, `url`, `name`) VALUES (NULL, '$file_url', '$name');"; //adding the path and name to database if(mysqli_query($con,$sql)){ //filling response array with values $response['error'] = false; $response['url'] = $file_url; $response['name'] = $name; } //if some error occurred }catch(Exception $e){ $response['error']=true; $response['message']=$e->getMessage(); } //displaying the response echo json_encode($response); //closing the connection mysqli_close($con); }else{ $response['error']=true; $response['message']='Please choose a file'; } } /* We are generating the file name so this method will return a file name for the image to be upload */ function getFileName(){ $con = mysqli_connect(HOST,USER,PASS,DB) or die('Unable to Connect...'); $sql = "SELECT max(id) as id FROM images"; $result = mysqli_fetch_array(mysqli_query($con,$sql)); mysqli_close($con); if($result['id']==null) return 1; else return ++$result['id']; } |
- Now test your script. You can use a rest client to test it I am using POSTMAN. See the below screenshot.
- If you are seeing the above response then. Your script is working fine. You can check the database and upload folder which you have created.
- So its working absolutely fine. Now lets move ahead and create a android project.
Creating Android Studio Project
We are done with the server side coding for this Android Upload Image Example. Now lets code our android application. Follow the steps given.
- Create a Android Studio Project.
- Create a class named Constants.java and write the following code. The following class contains the path to our php file which we created.  You are seeing two strings. The second it the path to the file we will create at the end of this post.
1 2 3 4 5 6 7 8 9 10 11 |
package net.simplifiedcoding.androidimageupload; /** * Created by Belal on 6/10/2016. */ public class Constants { public static final String UPLOAD_URL = "http://192.168.94.1/AndroidImageUpload/upload.php"; public static final String IMAGES_URL = "http://192.168.94.1/AndroidImageUpload/getImages.php"; } |
- You need to change the IP according to your system. To know the IP you can use IPCONFIG command in command prompt (windows user).
- Now we need to add android upload service to our project.
Adding Android Upload Service
- Go to your app level build.gradle file and add the following line inside dependencies block and sync your project.
1 2 3 4 5 6 7 8 9 10 |
dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) testCompile 'junit:junit:4.12' compile 'com.android.support:appcompat-v7:23.4.0' //Add this line compile 'net.gotev:uploadservice:2.1' } |
- Come to activity_main.xml and write the following xml code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
<?xml version="1.0" encoding="utf-8"?> <LinearLayout 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:orientation="vertical" 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="net.simplifiedcoding.androidimageupload.MainActivity"> <LinearLayout android:gravity="center_horizontal" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <Button android:id="@+id/buttonChoose" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Select" /> <EditText android:id="@+id/editTextName" android:hint="Name For Image" android:layout_weight="1" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <Button android:id="@+id/buttonUpload" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Upload" /> </LinearLayout> <ImageView android:id="@+id/imageView" android:layout_width="match_parent" android:layout_height="match_parent" /> </LinearLayout> |
- The above code will generate the following layout.
- As you can see we have two buttons, one to select image and other to upload image. We also have an EditText to enter the name for the image.
- Now come to MainActivity.java and write the following code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 |
package net.simplifiedcoding.androidimageupload; import android.Manifest; import android.content.Intent; import android.content.pm.PackageManager; import android.database.Cursor; import android.graphics.Bitmap; import android.net.Uri; import android.os.Bundle; import android.provider.MediaStore; import android.support.annotation.NonNull; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.Toast; import net.gotev.uploadservice.MultipartUploadRequest; import net.gotev.uploadservice.UploadNotificationConfig; import java.io.IOException; import java.util.UUID; public class MainActivity extends AppCompatActivity implements View.OnClickListener { //Declaring views private Button buttonChoose; private Button buttonUpload; private ImageView imageView; private EditText editText; //Image request code private int PICK_IMAGE_REQUEST = 1; //storage permission code private static final int STORAGE_PERMISSION_CODE = 123; //Bitmap to get image from gallery private Bitmap bitmap; //Uri to store the image uri private Uri filePath; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //Requesting storage permission requestStoragePermission(); //Initializing views buttonChoose = (Button) findViewById(R.id.buttonChoose); buttonUpload = (Button) findViewById(R.id.buttonUpload); imageView = (ImageView) findViewById(R.id.imageView); editText = (EditText) findViewById(R.id.editTextName); //Setting clicklistener buttonChoose.setOnClickListener(this); buttonUpload.setOnClickListener(this); } /* * This is the method responsible for image upload * We need the full image path and the name for the image in this method * */ public void uploadMultipart() { //getting name for the image String name = editText.getText().toString().trim(); //getting the actual path of the image String path = getPath(filePath); //Uploading code try { String uploadId = UUID.randomUUID().toString(); //Creating a multi part request new MultipartUploadRequest(this, uploadId, Constants.UPLOAD_URL) .addFileToUpload(path, "image") //Adding file .addParameter("name", name) //Adding text parameter to the request .setNotificationConfig(new UploadNotificationConfig()) .setMaxRetries(2) .startUpload(); //Starting the upload } catch (Exception exc) { Toast.makeText(this, exc.getMessage(), Toast.LENGTH_SHORT).show(); } } //method to show file chooser private void showFileChooser() { Intent intent = new Intent(); intent.setType("image/*"); intent.setAction(Intent.ACTION_GET_CONTENT); startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST); } //handling the image chooser activity result @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) { filePath = data.getData(); try { bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath); imageView.setImageBitmap(bitmap); } catch (IOException e) { e.printStackTrace(); } } } //method to get the file path from uri public String getPath(Uri uri) { Cursor cursor = getContentResolver().query(uri, null, null, null, null); cursor.moveToFirst(); String document_id = cursor.getString(0); document_id = document_id.substring(document_id.lastIndexOf(":") + 1); cursor.close(); cursor = getContentResolver().query( android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI, null, MediaStore.Images.Media._ID + " = ? ", new String[]{document_id}, null); cursor.moveToFirst(); String path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA)); cursor.close(); return path; } //Requesting permission private void requestStoragePermission() { if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) return; if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_EXTERNAL_STORAGE)) { //If the user has denied the permission previously your code will come to this block //Here you can explain why you need this permission //Explain here why you need this permission } //And finally ask for the permission ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, STORAGE_PERMISSION_CODE); } //This method will be called when the user will tap on allow or deny @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { //Checking the request code of our request if (requestCode == STORAGE_PERMISSION_CODE) { //If permission is granted if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { //Displaying a toast Toast.makeText(this, "Permission granted now you can read the storage", Toast.LENGTH_LONG).show(); } else { //Displaying another toast if permission is not granted Toast.makeText(this, "Oops you just denied the permission", Toast.LENGTH_LONG).show(); } } } @Override public void onClick(View v) { if (v == buttonChoose) { showFileChooser(); } if (v == buttonUpload) { uploadMultipart(); } } } |
- Finally add the storage and internet permission on your manifest.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="net.simplifiedcoding.androidimageupload"> <!-- add these permissions --> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsRtl="true" android:theme="@style/AppTheme"> <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> |
- Thats it now just run your app.
- Bingo! Its working absolutely fine. Now you may need to fetch the uploaded images.
Fetching the Uploaded Images
- To fetch the images inside your server side project, create one more file named getImages.php and write the following code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
<?php //Importing dbdetails file require_once 'dbDetails.php'; //connection to database $con = mysqli_connect(HOST,USER,PASS,DB) or die('Unable to Connect...'); //sql query to fetch all images $sql = "SELECT * FROM images"; //getting images $result = mysqli_query($con,$sql); //response array $response = array(); $response['error'] = false; $response['images'] = array(); //traversing through all the rows while($row = mysqli_fetch_array($result)){ $temp = array(); $temp['id']=$row['id']; $temp['name']=$row['name']; $temp['url']=$row['url']; array_push($response['images'],$temp); } //displaying the response echo json_encode($response); |
- This code will give you the following JSON.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
{ "error":false, "images":[ { "id":"1", "name":"Belal Khan", "url":"http:\/\/192.168.94.1\/AndroidImageUpload\/uploads\/1.jpg" }, { "id":"2", "name":"Belal", "url":"http:\/\/192.168.94.1\/AndroidImageUpload\/uploads\/2.jpg" }, { "id":"3", "name":"", "url":"http:\/\/192.168.94.1\/AndroidImageUpload\/uploads\/3.jpg" }, { "id":"4", "name":"Belal Khan", "url":"http:\/\/192.168.94.1\/AndroidImageUpload\/uploads\/4.jpg" } ] } |
- Now you can use the following tutorial to display the images using the above JSON.
Android Custom GridView with Images and Texts using Volley
- You can also get my source code from the link given below.
[sociallocker id=1372] [download id=”2974″]Â [/sociallocker]
So thats it for this Android Upload Image tutorial friends. You can also use this method to upload video and any type of file to your server. Leave your comments if having any doubts or feedbacks. Thank You 🙂