Android Upload Image using Android Upload Service

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.

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.

  • Now create a file named upload.php and write the following code.

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

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

  • Come to activity_main.xml and write the following xml code.

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

  • Finally add the storage and internet permission on your 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.

  • This code will give you the following JSON.

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

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 🙂

117 thoughts on “Android Upload Image using Android Upload Service”

  1. 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. 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
  3. 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
  4. How to upload the image that is captured with camera within the android application,, im getting trouble please help….

    Reply
  5. 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
    • 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
    • 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
  6. 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
  7. 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
  8. 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
  9. 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
  10. 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
  11. 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
  12. 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
    • 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
    • hi, i meet a same problem, and i find the it can be solve just through modify some segment.

      i modify code in line 33-40 to:
      // getting the file filename
      $filename = $fileinfo[‘filename’];

      //getting the file extension
      $extension = $fileinfo[‘extension’];

      //file url to store in the database
      $file_url = $upload_url . $filename . ‘.’ . $extension;

      //file path to upload in the server
      $file_path = $upload_path . $filename . ‘.’. $extension;

      these code segment let picture save use thire own filename, as if your picture named “boy.jpg”, it will upload to “AndroidImageUpload/uploads” with its own name “boy.jpg”.

      Reply
  13. 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
  14. 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
  15. 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
  16. 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
    • 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
  17. 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
  18. 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
  19. 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
  20. Hello , my name muhajir from indonesian , i want to ask , how to multiple upload file using library upload service ?
    thanks

    Reply
  21. 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
  22. 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
  23. 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
  24. 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
  25. 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
  26. 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
  27. 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
  28. 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
  29. 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
  30. Great job sir. It is too much helpful. Now my next step is to display the data in another activity. As the user click on the item from recyclerview all the data of selected item must be displayed in other activity. I only show Name and Image in the recyclerview. and want to display all of its data in other activity. How to do that?

    Reply
    • Hi hello

      Did you solve the issue even i am facing the same problem. The button is working fine in the emulator but when I build an apk and install in mobile that time button it is not working. Please help.

      Thank you.

      Reply
  31. I have problem with getPath function. I have copy paste your code, but it force close when i click button upload

    Reply
  32. Hey Belal, when i tried it on postman it shows this error how to fix it, i copying all of your codes and i dont know why it ‘s just error

    here’s the error :

    Warning: move_uploaded_file(uploads/4.PNG): failed to open stream: No such file or directory in
    D:\xampp\htdocs\opr57\upload.php on line
    45

    Warning: move_uploaded_file(): Unable to move ‘D:\xampp\tmp\php5602.tmp’ to ‘uploads/4.PNG’ in
    D:\xampp\htdocs\opr57\upload.php on line
    45

    {“error”:false,”url”:”http:\/\/192.168.43.149\/opr57\/uploads\/4.PNG”,”name”:”Bayu”}

    Reply
  33. Hello, i want to ask about something sir, when i upload it it says “Upload completed successfully” but there’s no image or data on my table, can you help me?

    Reply
  34. Hi Belal,
    I have one error if i can run the application in android 8 and above. If i trigger the upload function error will be generated. That error is Bad Request Foreground Notification. Please give any correct solution.
    Thanks and regards

    Reply
  35. Hello and thank you for this tutorial
    I’ve used the 4.5.1 version of net.gotev:uploadservice
    and i’m getting an error in :
    request.setNotificationConfig(new UploadNotificationConfig())

    the constructor of UploadNotificationConfig needs 6 parameters
    What shoud I do ?

    Reply
  36. Hi Belal
    No doubt your tutorials are great, can u modify the code or share us how to do upload with 4.5.1 specially due to change in UploadNotificationConfig, 2.6 does not support in latest android. Pls suggest how to set notification configuration as w/o this, i can not upload image.

    Reply

Leave a Comment