Simplified Coding

  • About
  • Contact Us
  • Advertise
  • Privacy Policy
You are here: Home / Android Application Development / Android Advance / Android Upload Image using Android Upload Service

Android Upload Image using Android Upload Service

June 10, 2016 by Belal Khan 97 Comments

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. You can also check the previous tutorials I posted about uploading images from android to server from the given links.

  • Android Volley Tutorial to Upload Image to Server
  • Android Upload Image From Gallery With Text
  • Android Upload Image to Server Using PHP MySQL

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.

android upload image database.jpg

  • 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.

dbDetails.php
PHP
1
2
3
4
5
<?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.

upload.php
PHP
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
<?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.

android upload image web service

  • 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.
android upload image database

Database

android upload image database

Upload Directory

  • 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.

Constants.java
Java
1
2
3
4
5
6
7
8
9
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
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.

activity_main.xml
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
<?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.

android upload image example

  • 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.

MainActivity.java
Java
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
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
<?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.

android upload image example 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.

getImages.php
PHP
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
<?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
{
   "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.

[download id=”2974″] 

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 🙂

Sharing is Caring:

  • Tweet
  • Share on Tumblr
  • More
  • Pocket
  • Print
  • Email

Related

Filed Under: Android Advance, Android Application Development Tagged With: android upload image, android upload image from gallery, android upload image to server

About Belal Khan

I am Belal Khan, I am currently pursuing my MCA. In this blog I write tutorials and articles related to coding, app development, android etc.

Comments

  1. Mahmudur Rahman says

    June 11, 2016 at 4:51 am

    Assala-mualikum, This is a best tutorial for upload image(base64) to server using volley library. Its done well. Now I want to upload pdf to use base64——– I want know is that possible to upload pdf base64?? ………… If possible I request you to upload a tutorial for pdf upload. Thank you for your great tutorial. Happy Ramadan…

    Reply
  2. pavithra says

    June 14, 2016 at 6:43 am

    “Oops you just denied the permission” this message is displaying,images are not uploading,how to slove this.

    Reply
    • Arun Karthigaivel says

      June 28, 2016 at 4:08 am

      Add permissions to manifest file.
      If on server side check username and password.

      Reply
      • vishal says

        July 6, 2017 at 4:44 am

        how to check username and password on server

        Reply
        • raji says

          August 10, 2017 at 2:13 am

          Your Code is working fine..i can able to upload image…only thing i couldnt able to upload parameter
          addParameter(“id”, uniqueid) //Adding text parameter to the request

          //php side
          $unique_id= $_POST[‘id’];

          Reply
  3. pavithra says

    June 14, 2016 at 6:49 am

    “Oops you just denied the permission” this toast is displaying ,images are not uploading

    Reply
    • Farah says

      May 12, 2017 at 1:53 pm

      follow same tutorial but Error during upload occur in notification…why?

      Reply
      • ck says

        April 23, 2018 at 1:06 am

        1. check that u have put tyour internet permission in manifest
        2. Check that your upload url is correct

        Reply
      • kidsmillennial says

        July 3, 2018 at 5:04 am

        Ya, I have the same problem. Why? I have checked with the upload url and also the internet permission already.

        Reply
  4. pavithra says

    June 14, 2016 at 7:18 am

    Oops you just denied the permission how to resolve these,pls help me .

    Reply
  5. pavithra says

    June 14, 2016 at 10:41 am

    deined permission message is displaying how to slove these

    Reply
  6. Ari says

    June 25, 2016 at 1:58 am

    nice article (y)
    sir,, can i request tutorial about how to implement Single Sign-On Android??
    thank u sir 🙂

    Reply
  7. nemanja says

    June 25, 2016 at 9:34 am

    Amazing tutorial guys It came exactly when I needed it to build upload for our app .. Fliiby << 🙂 will be live from July I hope 🙂
    I did a lot of modifications like loading images with glide since loading bitmap is memory heavy.. text immediately started lagging when I load 4-5mb picture.. changed notifications system etc… but guys thanks again it helped me a lot..

    ==glide change for image=====

    @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();

    Glide.with(getApplicationContext())
    .load(filePath)
    .diskCacheStrategy(DiskCacheStrategy.ALL)
    // .fitCenter()
    .centerCrop()
    .crossFade(500)
    .priority(Priority.HIGH)
    .into(imageView);

    }
    }

    Reply
  8. Avinash Yadav says

    June 29, 2016 at 12:38 pm

    Hi Belal,
    I am following your tutorials and these are very helpful for me, Thank you for tutorials.
    I want the code for downloading pdf file which is stored in my database.
    Could you please write the code and upload it for me.

    Reply
  9. Kamla Sharma says

    June 30, 2016 at 10:35 am

    How to upload the image that is captured with camera within the android application,, im getting trouble please help….

    Reply
  10. Paul Peridis says

    July 19, 2016 at 5:03 pm

    Belal Khan your tutorial is fantastic. It is easy to comprehend and implement. However I am getting this error in the error log in the server
    “mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given in /…………../AndroidUploadImage/upload.php on line 78”

    I am using postman exactly as you show and I am getting no responce and status 200 OK.

    What could be the issue here?
    Thanks in advance.

    PS. In your tutorial you use AndroidUploadImage, but in your code you use AndroidImageUpload. Some people will scratch their head if they copy the code and find out it doesn’t work.

    Reply
  11. jay says

    July 21, 2016 at 11:45 am

    name and url are uploaded in mysql. but image is not uploading in the folder when i run the php code in postman.

    Reply
    • Daniel Prado says

      May 23, 2017 at 10:11 pm

      I had the same error and what i did is to copy any image that you have and paste it in that folder and name it with the previous id, for example if your last register in database is 12 that image have to have that number, and now try to do upload again a picture using the app and it might work.

      Reply
    • Rahul Soshte says

      August 2, 2017 at 9:13 am

      1.Check if the client has necessary permission for uploading files.
      2.Check your PHP Configuration File To Check File Size Upload Limit/No Of Files/Temp Directory and Change according to your requirement.

      Reply
  12. Sumit Das says

    August 1, 2016 at 5:05 pm

    its not able to connect the http server

    Reply
  13. brendah says

    August 17, 2016 at 6:39 am

    getting the error on android device. File Upload Error during upload

    Reply
  14. CK says

    August 22, 2016 at 9:28 am

    Everything is working well for me, except one thing. supposing someone chooses not to select an image for upload, but clicks the upload button, the app crashhes! How do I prevent the app from crashing? prompting the user “please select an image”

    Reply
    • Eman says

      April 11, 2018 at 9:59 pm

      Have you found any solution?

      Reply
  15. Andro CG says

    September 7, 2016 at 11:31 pm

    It’s a pity … The upload is done but the pictures do not advance to the uploads folder. What should be done ?

    Reply
  16. Andro CG says

    September 8, 2016 at 8:20 pm

    Error in line 79 :
    Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given in C:\wamp\www\phpcode\upload.php on line 79

    Reply
  17. Rani says

    September 14, 2016 at 11:26 am

    I have doubts to upload the audio on server. plz help me

    Reply
  18. mahesh kariya says

    September 15, 2016 at 5:35 pm

    bas bhai aise hi kam kiya kar..osm

    Reply
  19. maiku says

    September 27, 2016 at 9:27 pm

    Thanks!!!

    Very helpful

    Reply
  20. sachin says

    September 29, 2016 at 12:29 pm

    I am getting error while uploading …is error in upload at notification area.

    Reply
    • Eman says

      April 12, 2018 at 12:40 pm

      Have you found any solution?

      Reply
  21. tao says

    October 8, 2016 at 1:35 am

    i can ‘t get the file path from the gallery application keeps crashing when i i try to upload . Error on the console shows that the method getpath() is not returning the image

    Reply
  22. steve says

    October 17, 2016 at 2:09 pm

    No longer working in Android 6.0

    Reply
    • Belal Khan says

      October 17, 2016 at 2:18 pm

      You need to ask storage permission at run time to make it work on >android 5
      Check this tutorial to know how https://www.simplifiedcoding.net/android-marshmallow-permissions-example/

      Reply
  23. August says

    October 18, 2016 at 12:45 pm

    Hello Belal. I got error Please choose a file in Postman. Please help

    getMessage();
    }
    //displaying the response
    echo json_encode($response);

    //closing the connection
    mysqli_close($con);
    } else {
    echo $response[‘error’]=true;
    echo $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(){
    $sql = “SELECT max(notesID) as notesID FROM notes”;
    $result = mysqli_fetch_array(mysqli_query($con,$sql));

    mysqli_close($con);
    if($result[‘notesID’]==null)
    return 1;
    else
    return ++$result[‘notesID’];
    }
    ?>

    Reply
    • August says

      October 18, 2016 at 12:49 pm

      sorry the code went crazy. here in pastebin http://pastebin.com/MygkttBm

      Reply
  24. AbeerAlRumaidh says

    October 21, 2016 at 3:17 pm

    I tried the php code in POSTMAN and everything is fine and i tried the code in android studio and it is working fine but once i upload the image, i get this “Error during upload”. please help

    Reply
  25. Neha Abdulla says

    October 22, 2016 at 4:44 am

    I used the same method for uploading image into filezilla server. Everything is fine but the image is not uploading into the folder created in filezilla. can you please help me?

    Reply
  26. Rakesh says

    November 12, 2016 at 10:35 am

    Hello Bilal,

    I followed your tutorial and uploads are going through(even a 5 mb image goes through successfully. However, when i uppload another image, it overwrites the previous image. The first image was uploaded as 1.jpg. Then I uploaded a .png file and it was saved as 1.png. But when I try uploading more jpg files, it only overwrites and does not increment the number to 2 and so on. I also noticed my table returns no rows after this. Any help is appreciated. Thanks.

    Reply
    • Akhil says

      January 3, 2017 at 8:05 am

      Hi Rakesh
      I am too Stuck on This Do You find the Solutions What Wrong here….Do you have any notions how to calculate response from server in the activity

      Reply
  27. Edwin Adeola says

    November 15, 2016 at 4:05 am

    Hi Mr. Belal!

    I appreciate your tutorial so much and it has helped me to build a good android app which I will be asking you to download and assess for improvement.

    I an using this example to upload an image but I don’t want the image to be displayed on the activity but the filepath to be set on the edittext. In the process, I realised that you are not setting the filepath on the edittext.

    Kindly check you observation and respond.

    Thanks and regards.

    Reply
  28. Prashanth says

    November 19, 2016 at 6:46 pm

    hey!
    i want to upload a image to asp.net server
    i want to know the server side code also.

    Reply
  29. RaviKant says

    December 8, 2016 at 11:21 am

    Why i am getting my image compressed?
    can you give me idea?
    its not the same size size i uploaded.

    Reply
  30. Usman says

    December 13, 2016 at 10:38 am

    What if 2 or more than 2 user upload images with same name like 1.jpg then how can we differentiate in them?

    Reply
  31. Jerry says

    December 16, 2016 at 4:31 am

    Nice tutorial, one question, how do you set headers for authorization in this method?

    Reply
  32. Rahul Manjinder says

    December 23, 2016 at 3:33 pm

    Thanks Bro You are my saviour.
    and once again thank u very very very very very very very very very very very very much

    Reply
  33. Tarun says

    December 30, 2016 at 1:30 pm

    How to Upload file in Jsonobject with upload service

    Reply
  34. Avinash Singh says

    January 3, 2017 at 12:30 pm

    Hi,
    Belal sir ,i am using image upload but some error to solution is tough in ,i am copy our website but no solution please help image upload in android studio

    Warning: move_uploaded_file() [
    function.move-uploaded-file]: It is not safe to rely on the system’s timezone settings. You are *required* to use the date.timezone setting or the date_default_timezone_set() function. In case you used any of those methods and you are still getting this warning, you most likely misspelled the timezone identifier. We selected ‘Asia/Calcutta’ for ‘IST/5.0/no DST’ instead in
    /home/celeadmn/public_html/demo/upload.php on line
    31

    Warning: move_uploaded_file(uploads/12.html) [
    function.move-uploaded-file]: failed to open stream: No such file or directory in
    /home/celeadmn/public_html/demo/upload.php on line
    31

    Warning: move_uploaded_file() [
    function.move-uploaded-file]: It is not safe to rely on the system’s timezone settings. You are *required* to use the date.timezone setting or the date_default_timezone_set() function. In case you used any of those methods and you are still getting this warning, you most likely misspelled the timezone identifier. We selected ‘Asia/Calcutta’ for ‘IST/5.0/no DST’ instead in
    /home/celeadmn/public_html/demo/upload.php on line
    31

    Warning: move_uploaded_file() [
    function.move-uploaded-file]: Unable to move ‘/tmp/phpUbekSp’ to ‘uploads/12.html’ in
    /home/celeadmn/public_html/demo/upload.php on line
    31

    {“error”:false,”url”:”http:\/\/www.celebritiesacademy.com\/Androidimageupload\/uploads\/12.html”,”name”:”aafhyh”}

    Reply
  35. Ponglang Petrung says

    January 9, 2017 at 10:21 am

    ok clear you check to commend line to write cmd and you set ipconfig/all ,

    Ex : http://192.168.143.2/AndroidImageUpload/upload.php // ip you = 192.168.143.2

    pic: http://upload.i4th.in.th/th/download.php?id=587363531

    you ok

    Social : Android Developer Library GitHub
    : https://www.facebook.com/groups/883546485084033/?fref=ts

    Reply
  36. Shubham Thakur says

    February 2, 2017 at 4:20 am

    Hi Belal ,
    You have an awesome website and more than that you are an awesome blog writer because of the efforts that you are taking.

    I have been using your code for some time now.

    I would love to see a tutorial from you on same thing as https://www.simplifiedcoding.net/android-volley-tutorial-to-upload-image-to-server/

    but i want to be able to use camera as well.

    Thank you for making world a great place.

    Reply
  37. Subagjo says

    February 8, 2017 at 4:05 pm

    How to get JSON Object Response message when it Success or Failure , Thank you 😀

    Reply
  38. Subagjo says

    February 8, 2017 at 4:18 pm

    Hy Belal , thank you
    this tutorial work for me , but how i can get Json Object request to notify me in activity when upload image is succes or failure

    Reply
  39. parastoo razi says

    February 9, 2017 at 6:12 am

    Hi Belal khan
    Thanks because of your perfect codes
    i run this code bud i have problem with upload and error with upload
    i check every thing more and more but i’m going to crazy
    please help me

    Reply
  40. Wildan says

    February 15, 2017 at 9:59 am

    Hi, belal..
    This code is very helpfull, i want to know about if i want to upload more than 1 file in 1 proccess

    Thanks

    Reply
    • Ponglang Petrung says

      February 16, 2017 at 8:46 am

      you create code java method more to send image and you edit for

      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();

      to

      new MultipartUploadRequest(this, uploadId, Constants.UPLOAD_URL)
      .addFileToUpload(path, “image”) //Adding file
      .addFileToUpload(path, “image”)
      .addFileToUpload(path, “image”)
      .addFileToUpload(path, “image”)
      .
      .
      .
      to

      new MultipartUploadRequest(getContext(), uploadId, Constants.UPLOAD_URL)
      .addFileToUpload(path, “image”) //Adding file
      .addFileToUpload(path, “image”) //Adding file
      .addFileToUpload(path, “image”) //Adding file
      .addFileToUpload(path, “image”) //Adding file
      .addParameter(“pea_id”, pea_id) //Adding text parameter to the request
      .addParameter(“name”,URLEncoder.encode(inspect, “UTF-8”))
      .addParameter(“latitude”, Latitude)
      .addParameter(“longitude”, Longitude)
      .addParameter(“description”,URLEncoder.encode(ValueHolderSpinner, “UTF-8”))
      .addParameter(“date”, date)
      .setNotificationConfig(new UploadNotificationConfig())
      .setMaxRetries(2)
      .startUpload(); //Starting the upload

      Reply
  41. SHUBHAM SRIVASTAVA says

    March 2, 2017 at 7:47 am

    how can i show successfully uploaded message in my activity

    Reply
  42. Aqit says

    March 2, 2017 at 4:03 pm

    How to shrink teh size image before upload ? Please help me

    Reply
  43. AndroCg says

    March 3, 2017 at 1:39 pm

    How do I send two simultaneous images? What changes will be made to the php code? Thank you

    Reply
  44. Malin says

    March 6, 2017 at 4:54 am

    How to compress image before upload ?

    Reply
  45. Abdul says

    March 13, 2017 at 1:15 am

    one i click on upload button it’s showing error ” Unfortunately AndroidImageUpload has stopped work.

    Reply
  46. Brahmjeet Tanwar says

    March 17, 2017 at 6:11 pm

    Sir thank u so much, only you made it possible,
    i tried number of methods tutorials but no one helped and you just wrote the code in such a simplified manner that beginners like us can understand very easily moreover you made this possible to upload the images to server otherwise many of us were in trouble to how to upload images to server i will follow you everywhere nowonwards , such a great help to me for making my minor project .
    thank u so much sir!

    Reply
  47. AndroCG says

    March 19, 2017 at 11:37 am

    Hello Belal, Would there be a possibility to upload two images and assign them names instead of incrementing numbers? If so, how to proceed on the PHP file?

    Reply
  48. sandeep gandhasiri says

    March 30, 2017 at 8:53 am

    How to upload songs(mp3) to the xampp server?
    using this methods

    Reply
  49. Daksh Agrawal says

    April 1, 2017 at 6:00 pm

    Pls provide a query for creating table in MySql….it will make it easy to use

    Reply
  50. Rohit M L says

    April 3, 2017 at 11:55 am

    Hi , can u just mail me ( [email protected] )the complete zip file of this project. I downloaded the project zip from your blog but i cant find the some java files .

    Reply
  51. A B Sagar says

    April 11, 2017 at 1:01 pm

    worked like charm

    Reply
  52. peyman says

    April 20, 2017 at 6:56 am

    Hi Belal,
    Thankyou for Tutorial,

    How to Delete uploaded image in mysql and server (host)with android app?

    Reply
  53. Aman says

    May 7, 2017 at 6:52 am

    Hello Sir, I have an error in this code is if we run this without validation means if we not select any file then it asking please select file and data cannot be submitted but i want to make a choice for the user that if user wants to select image or if user not want then it skip but the data will be submitted but this tsk is not performed..

    Reply
  54. muhajir says

    May 7, 2017 at 5:38 pm

    Hello , my name muhajir from indonesian , i want to ask , how to multiple upload file using library upload service ?
    thanks

    Reply
  55. Farah says

    May 12, 2017 at 1:54 pm

    error during upload ..why ??

    Reply
  56. Pandu says

    June 11, 2017 at 7:59 am

    Upload success but data not inserted in database

    Reply
  57. Abdul Kadir says

    June 28, 2017 at 12:08 pm

    In the notification bar I’m getting an error during upload. Has anyone solved this issue? Can someone please help me with this? Many thanks.

    Reply
  58. vishal says

    July 6, 2017 at 4:51 am

    Please sir ,I want to know how to upload image on a cpanel server ….i am fresher in an company

    Reply
  59. Anmol Gupta says

    August 9, 2017 at 6:09 am

    hello sir ur program is showing cursor out of bound exception:

    Reply
    • Belal Khan says

      August 9, 2017 at 5:50 pm

      Have you tried downloading my code?

      Reply
  60. Reva says

    August 11, 2017 at 11:23 am

    Where is service?

    Reply
    • Belal Khan says

      August 13, 2017 at 9:10 am

      Android Upload Service is the name of the library we are using here

      Reply
  61. Conor Smith says

    August 15, 2017 at 10:30 pm

    Hey Belal,

    Thank you the tutorial but I am having some trouble getting it running. When I hit upload, the app crashes. After some inspection, it seems the cursor in getPath() is empty. This is the redefinition of the cursor that is empty, so the cursor defined as: cursor = getContentResolver().query(
    android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
    null, MediaStore.Images.Media._ID + ” = ? “, new String[]{document_id}, null);

    I’m not sure how to fix this. Any help would be much appreciated!

    Reply
  62. ADARSH GUPTA says

    August 19, 2017 at 3:12 pm

    new MultipartUploadRequest(this, uploadId, SyncStateContract.Constants.UPLOAD_URL)

    here in above line UPLOAD_URL shows error.I make class constants but it is showing that it is never used.

    Reply
  63. IAN says

    September 7, 2017 at 6:33 pm

    hey! nice post!

    I’m trying to upload an image from gallery, I’ve allready tested the php on Postman and succesfully upload an Image in my server and updated my DataBase.

    When it comes to android……

    try {
    String uploadId = UUID.randomUUID().toString();

    new MultipartUploadRequest(this, uploadId, URL_PHP”)
    .addFileToUpload(path, “image”) //Tomar archivo
    .addParameter(“name”, name) //guardar parametro nombre
    .setNotificationConfig(new UploadNotificationConfig())//notificacion en barra para carga
    .setMaxRetries(2)
    .startUpload(); //Iniciar la carga
    Toast.makeText(this, “si tomo el archivo y si lo busco en php”, Toast.LENGTH_SHORT).show();
    } catch (Exception exc) {
    Toast.makeText(this, exc.getMessage(), Toast.LENGTH_SHORT).show();
    }

    The app is showing how the file is uploading, but when it finishes… the notification is: “Error during Upload”

    where am I wrong?

    Im testing on android 5.1

    Reply
    • IAN says

      September 12, 2017 at 3:57 pm

      Using packet Capture…… it throws:
      HTTP/1.1 403 Forbidden

      How can I fix it?

      Reply
  64. Aftab Mondal says

    September 19, 2017 at 1:22 pm

    Nice Work Bro. Thank you

    Reply
  65. Sunil says

    October 7, 2017 at 3:02 pm

    I’m trying to use this code in fragment but I’m getting error “cannot resolve symbol MultipartUploadRequest” , “cannot resolve symbol UploadNotificationConfig” and “cannot resolve symbol UPLOAD_URL” in

    public void uploadMultipart() {
    //getting name for the image
    String name = FullName.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(getActivity().getApplicationContext(), uploadId, SyncStateContract.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(getActivity().getApplicationContext(), exc.getMessage(), Toast.LENGTH_SHORT).show();
    }
    }

    Reply
    • Auston Ajith says

      May 12, 2018 at 7:32 am

      compile ‘net.gotev:uploadservice:2.1’

      Reply
  66. Chander says

    November 29, 2017 at 7:04 pm

    I followed every step very carefully around 5-7 times, but not able to upload image. I have Ubuntu 16 server. I tried with Postman that is also not working for me. I really need help.
    In Php file If I write print_r($_POST); it show everything is perfect in $_POST, but when we get $_POST[‘name’] and other values, they comes as empty. Means print_r($_POST[‘name’]); prints nothing.

    Can anyone help
    Great Thanks.

    Reply
  67. Hardik says

    February 24, 2018 at 8:21 am

    Belal I want to show the response message in alert dialog. I don’t want Notification config how can i do this. Please help

    Reply
  68. anum says

    March 10, 2018 at 7:58 pm

    hey! I want same thing to upload audio file so which changes are required for this

    Reply
  69. Archana says

    April 6, 2018 at 6:16 pm

    hello i am getting error like “Error During Upload” but dnt know how to recove this

    Reply
    • Eman says

      April 12, 2018 at 12:44 pm

      Have you found any solution?

      Reply
  70. ANUP says

    June 5, 2018 at 9:52 am

    I NEED THE SERVER RESPONSE…

    Reply
  71. ilyas says

    August 20, 2018 at 7:29 am

    where is below link bro.. ? There is no L:ink Shown..

    Reply
  72. Manikandan says

    August 21, 2018 at 8:33 am

    If i will upload the image in mylocal host server, how to find out that image file in my host?

    Reply
  73. Muhammad Luqman says

    September 5, 2018 at 10:49 am

    Hi bro Thanks I follow your tutorials it help alot and I learn more things and coding techniques I have one question if you can can make tutorials on it its very important and helpful for others
    My question:
    I have follow this tutorial and I have done my task but I want to run this application on my android mobile and I send all data from Mobile to laptop, Laptop use as server I am use wamp so is that possible, if so please make tutorial and show to send run same application on mobile and all data send from mobile to laptop instead of emulator using Wifi connection

    Reply
  74. axar lotwala says

    September 26, 2018 at 6:54 am

    i am follow same process but image view in same image show on time choose but the upload time they did not choose time image but upload in another image please help us

    Reply
  75. ashwini says

    October 5, 2018 at 7:58 am

    hello
    i am using windows.i dont have postman.what are the alternatives for postman to run the code??

    Reply
    • Belal Khan says

      November 20, 2018 at 6:54 am

      you can install postman in windows too.

      Reply
  76. Khan says

    October 13, 2018 at 10:21 am

    if image size is exceeded from 4MB then code not working. any other solution…

    Reply
  77. Jajang Jaenal Yusup says

    November 15, 2018 at 10:40 pm

    Hello, nice article but i faced problem when use setNotificationConfig the error like (android.app.RemoteServiceException: Bad notification for startForeground: java.lang.RuntimeException: invalid channel for service notification). How to fix it please…

    Reply

Leave a Reply to IAN Cancel reply

Your email address will not be published. Required fields are marked *

Search




Download our Android App

Simplified Coding in Google Play

About Me

Belal Khan

Hello I am Belal Khan, founder and owner of Simplified Coding. I am currently pursuing MCA from St. Xavier's College, Ranchi. I love to share my knowledge over Internet.

Connect With Me

Follow @codesimplified
Simplified Coding

Popular Tutorials

  • Android JSON Parsing – Retrieve From MySQL Database
  • Android Login and Registration Tutorial with PHP MySQL
  • Android Volley Tutorial – Fetching JSON Data from URL
  • Android Upload Image to Server using Volley Tutorial
  • Android TabLayout Example using ViewPager and Fragments
  • Retrieve Data From MySQL Database in Android using Volley
  • Firebase Cloud Messaging Tutorial for Android
  • Android Volley Tutorial – User Registration and Login
  • Android Upload Image to Server Using PHP MySQL
  • Android Navigation Drawer Example using Fragments




About Simplified Coding

Simplified Coding is a blog for all the students learning programming. We are providing various tutorials related to programming and application development. You can get various nice and simplified tutorials related to programming, app development, graphics designing and animation. We are trying to make these things simplified and entertaining. We are writing text tutorial and creating video and visual tutorials as well. You can check about the admin of the blog here and check out our sitemap

Quick Links

  • Advertise Here
  • Privacy Policy
  • Disclaimer
  • About
  • Contact Us
  • Write for Us

Categories

Android Advance Android Application Development Android Beginners Android Intermediate Ionic Framework Tutorial JavaScript Kotlin Android Others PHP Advance PHP Tutorial React Native

Copyright © 2017 · Simplified Coding· All rights Reserved. And Our Sitemap.All Logos & Trademark Belongs To Their Respective Owners·

loading Cancel
Post was not sent - check your email addresses!
Email check failed, please try again
Sorry, your blog cannot share posts by email.