Android Upload file to server using PHP, MySQL

In this Android Upload File to Server tutorial, we are going to discuss about how to select a file in android and upload it to the server using New Android Studio. Using the following code, we can successfully upload images, videos, documents, zip files, etc.. to the server. The code is tested for files upto 10MB of size.

android upload file to server featured logo

The complete code to demonstrate Android Upload file to server can be cloned/downloaded from the github repo below:

android upload file to server github repo link

Note: In order for the above code to work, you need to  place php file (given in the project) in your own server/testing environment.

Android Upload file to Server:

For this tutorial, I have created a New Project Named UploadFileToServer. Now let us first declare the permissions required in our Android Manifest file.

The above permissions are required to access Internet and to Read Android External Storage files.

I have written the following code in activity_main.xml:

Now create a java class named FilePath.java and add the following code to it:

The above class is used to return the file path of the selected document/ video / audio etc..

Now we declare the MainActivity.java as follows:

The above code is commented wherever it is necessary. In this MainActivity.java, we wired up the attachment icon, Textview and Upload button and coded them such that when the icon is clicked, we can select the required file so that the textview gets updated with the path of the selected file. When we click on Upload button, a ProgressBar appears indicating that the file is being uploaded to the server. After the upload, the ProgressBar disappears and the textview gets updated detailing where the file has been uploaded in the server.

Server Side PHP Script for Android Upload File to Server:

Now create a serverside PHP Script that allow Android Upload file to server. Here I named it UploadToServer.php and added the following code:

I have placed the above file in Coderefer.com/extras folder. The above code creates a new folder named uploads and places the files being uploaded to uploads folder.

Vamsi Tallapudi
Connect Via

Vamsi Tallapudi

Founder and Author at Code Refer
Android Dev, Tech Enthusiast and Blogger. Ever since my first basic android app has reached lakhs of users, I've found myself in love with Android Development :). While my primary passion is coding, during my free time, you can find me blogging, travelling or on Facebook 🙂
Vamsi Tallapudi
Connect Via

Related Posts

Vamsi Tallapudi

Android Dev, Tech Enthusiast and Blogger. Ever since my first basic android app has reached lakhs of users, I've found myself in love with Android Development :). While my primary passion is coding, during my free time, you can find me blogging, travelling or on Facebook :)

You may also like...

  • Waseem

    Hi Vamsi, i want to add more parameters while posting a image do u knw how can i do that from the above code??

  • chirag gandhi

    Thank you so much sir it was very helpful for me.
    sir i hv an query that
    what should i do if i want to rename the file to the particular string. and then the file is upload with the new name on the server..

  • Hansol Lee

    This tutorial was very useful.
    I have one question i need to ask you.
    I want to know how to download file to Android.
    plz answer me

  • Omaima Tauqeer

    Hello Hansol. i want to ask do you have a working code of uploading file on server?
    i would be really thankful to you if you provide me with the source code
    regards.

  • Eric

    Is there a reason why the php portion of this wouldn’t work or be able to find anything? I’m able to successfully go through the whole process, access the file, get it’s path and perform the connection and receive a response by asking for the getInputStream() but my server can’t find anything using your code for php. I left the variable names the same and literally copied and pasted the php code exactly.. I just can’t figure out why it thinks nothing is there. If I try to var_dump($_FILES[‘uploaded_file’]) it says that it’s null.

  • Hansol Lee

    I wrote the above code. it is gonna work fine.

  • Özgür

    Hello, Can you make this work with mysql? Like uploading file to a server and inserting the URL to the mysql with the uploader username?

  • Clarissa Carcha

    the php file won’t work.

  • Pingback: Android Templates and advance concepts – vaidehipjoshi25()

  • Oumnia Boualou

    thanks for the tutorial but i get this error application introuvable pour exécuter cette action any idea??

  • Pradipto Karmakar

    Thanks for the tutorial.
    I downloaded your project from site and ran it on my phone. After opening the file chooser any type of the file was not getting selected(like all files appeared faded which could not be clicked). Please give a solution to my problem.

  • paciopak

    I have same problem. Any help?

  • Apurv

    hello sir,can u tell that where can i put my parameters?

  • atlasica

    Great article, much appreciated!

    Some help for previous commenters and future readers –

    Issue: Grayed-out files in file chooser.
    Possible solution: Modify line 78 of MainActivity.java. I changed it to “intent.setType(“image/jpeg”) to better suite my use case.

    Issue: HTTP 200 (OK) but uploaded file nowhere to be found when using your own server.

    Possible solution: Fix your target folder permissions.

  • Apurv

    great work,
    But i stuck at passing second parameter.can anyone tell me that how to pass second parameter?

  • kinsley kajiva

    dude just using your knowledge on how to do it in php as if it was web design..

  • f2k

    nice post..
    am new to android and used your codes but when i click attachment icon i get a popup which says” No apps can perform this action” and i have tried in two different android phones but it still appear the same..
    what should i do? help please

  • What will be the max file size?

  • Harsh Malhotra

    not able to post string along with it

  • sethu

    Good article…was really helpful Thanks Vamsi!!

  • Hemanth Kumar

    Hi sir
    Thank you so much for the above article.
    i was struct from last 2 days for upload file to server. finally i got this

    But i am getting one problem
    i am not able to upload to the server.
    not able to see the file in hosting

    Please help me

  • Usama Munir

    Hi Sir…I have this problem…Can you plz guide me how to resolve this error https://uploads.disquscdn.com/images/050e39d823e5dbecfcccd41843fc2746e46bb260f99ae16ab0e1c5b5de3d5824.png ?…i just copied your code and past it…

  • Amshu

    Even I am facing same problem.How to solve this?

  • try using
    intent.setType(“*/*”); instead of “file/*”
    in 78th line of MainActivity.java file to solve the issue.

  • hi, try using
    intent.setType(“*/*”); instead of “file/*”
    in 78th line of MainActivity.java file to solve the issue.

  • Amshu

    Thank u so much.Here if I select file from sd card,it is showing “Cannot upload file to server”.Is it possible to upload file from sd card using same code or any changes are there?

  • Bliss Hu

    This code does not work whatsoever on API level 23. You have to check for the permissions at runtime and this code does not implement that. Whoever says this is working is on some outdated API level. It says that this post was updated a week ago, but it’s not.

  • Sam Boychuk

    Hi Vamsi, love the solution, but the PHP script is pretty open to exploitation. You probably want to upload outside the webroot (or at the very least lock that directory down using .htaccess). If you don’t any manner of file can be uploaded to allow a third party to create a php terminal.

  • chamuella

    I am Korean. Please understand that English is awkward.

    I received a lot of help. Thank you.
    When uploading a non-English file, it is saved as “@”

    I would really appreciate it if you could help with this.T_T
    https://uploads.disquscdn.com/images/bb7a6b4f822a0da80efe5f16295fa24afe34275de8c13802053a3d73b2665ac7.jpg
    SERVER: PHP 5.2 UTF-8
    ANDROID: UTF-8

  • chamuella

    THANKS THANKS TTTTTTTHANKS!!!

  • Kil Kal

    I implemented this code with Asynctask, picture-taking and some other stuff. https://github.com/AndresNamm/AndroidUploadImage Serverside stays the same. Good tutorial!!

  • Gamal Sebaee

    How can return data from server and show it in this function
    i need to return saved image name after uploaded to server to show it in mobile app

  • Syawqi Muhammad

    hi sir,
    i have a problem, i will send name,address,phone too… how i can send them with this method?

  • Cspavithra Gowda

    It was Awesome tutorial sir ,it worked for me ,thanks a lot sir

  • Mayur Dusane

    Thanks bro. You saved my whole day. Awesome script

  • Rishab Surana

    Sir everything is fine except video and pdf file response is 500 from server(Internal server error) please help

  • mali

    Hi sir,
    nice example, there is small error while uploading file on server, how to solve this error, please explain me
    W/System.err: java.io.FileNotFoundException: /storage/emulated/0/Download/lordkrishna.mp3 (Permission denied)
    W/System.err: at java.io.FileInputStream.open(Native Method)
    W/System.err: at java.io.FileInputStream.(FileInputStream.java:146)
    W/System.err: at com.example.moraya.upload1.MainActivity.uploadFile(MainActivity.java:142)
    W/System.err: at com.example.moraya.upload1.MainActivity$1.run(MainActivity.java:65)
    W/System.err: at java.lang.Thread.run(Thread.java:761)
    E/EGL_emulation: tid 2422: eglSurfaceAttrib(1174): error 0x3009 (EGL_BAD_MATCH)
    W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0x968f1180, error=EGL_BAD_MATCH
    E/EGL_emulation: tid 2422: eglSurfaceAttrib(1174): error 0x3009 (EGL_BAD_MATCH)
    W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0x968f1240, error=EGL_BAD_MATCH

    Thank you so much

  • ryan munene

    Hi
    what if i have two attachments in one screen,can the method onActivityResult be duplicated to allow multiple uses in the same page please help
    thanks!

  • raga vendra

    You may give your custom path of the image or file etc.

  • raga vendra

    10 mb

  • raga vendra

    Give permission to the app in your mobile

  • Marat Kuznecsov

    If you want to send multiple parameters, replace

    //+++++++++++++++

    //writing bytes to data outputstream
    dataOutputStream.writeBytes(twoHyphens + boundary + lineEnd);

    dataOutputStream.writeBytes(“Content-Disposition: form-data; name=”uploaded_file”;filename=”” + selectedFilePath + “”” + lineEnd);
    dataOutputStream.writeBytes(lineEnd);

    //+++++++++++++++

    replace:

    //++++++++++++++

    //writing bytes to data outputstream
    dataOutputStream.writeBytes(twoHyphens + boundary + lineEnd);

    int photo_id = 1;

    dataOutputStream.writeBytes(“Content-Disposition: form-data; name=”photo_id”” + lineEnd + lineEnd); // param name
    dataOutputStream.writeBytes( photo_id + lineEnd + twoHyphens + boundary + lineEnd); // param value

    String photo_name = “My First Photo”;

    dataOutputStream.writeBytes(“Content-Disposition: form-data; name=”photo_name”” + lineEnd + lineEnd); // param name
    dataOutputStream.writeBytes(photo_name + lineEnd + twoHyphens + boundary + lineEnd); // param value

    dataOutputStream.writeBytes(“Content-Disposition: form-data; name=”uploadfile”;filename=””+ selectedFilePath + “”” + lineEnd);
    dataOutputStream.writeBytes(lineEnd);

    //++++++++++++++

  • ramukaka

    I am new to android..I get the following message after i say upload
    Server Response is: Forbidden: 403

  • muhamad aminruddin

    Why i can’t see my uploaded file in my server.but this app showing message that im successfully upload the file

  • muhamad aminruddin

    Thanks!!!Great Work!! I can upload to my localhost and domain but at my linux server seem doesn’t work

  • Sujeet Kumar

    i am getting a message in Toast ” File not found ” .
    when i pick up file from device.

  • Eki Rifaldi

    https://uploads.disquscdn.com/images/c721f0cc525f53b50c3bf84184d1d3732290adccd8371e3b5774a043ade4379b.jpg

    How to fix this? In Application, File Not Found.. In program, Permission denied.
    I’ve used

  • Cspavithra Gowda

    Thank you so much sir it was very helpful for me.
    sir i hv an query that
    what should i do if i want to rename the file to the particular string. and then the file is upload with the new name on the server..

  • Taufan Nanda Luzanil

    Worked!!! Thank you so much sir, it was very helpful for me.

  • Steve Curtis

    Means you have to request and check for runtime permissions. Check out this library to help with that: https://github.com/googlesamples/easypermissions

  • Steve Curtis

    You need to declare/check for runtime permissions. This library will help: https://github.com/googlesamples/easypermissions

  • narendra kumar

    Sir i am getting File not found after click on upload button.Please help me why it is giving such type error.
    In logcat it is showing this error
    java.io.FileNotFoundException: /storage/emulated/0/Android/data/net.one97.paytm/files/Download/Invoice3369664106.pdf: open failed: EACCES (Permission denied)

  • Siderra Victor

    Hi @vamsikrishnatallapudi:disqus how do I limit the files to be chosen to only the csv format?

  • Siderra Victor

    I am getting the same error.Did you solve it?

  • Siderra Victor

    Steve Curtis can you please elaborate?The library still doesnt seem to help

  • Sudhakar Annadurai

    custom path means

  • Siderra Victor
  • Siderra Victor

    @vamsikrishnatallapudi:disqus

  • Mahesh Lad

    how to receive file in asp.net

  • barasa

    bro, sometimes, when i use move_uploaded_file

    failed upload several image. Sometimes uploaded, sometimes not.