Android Upload File to Server

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

Note:

The link to download the complete code for the following tutorial is given at the bottom of this article.

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:

[widget id=”text-3″]

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:

[widget id=”text-3″]

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.

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

Click here to download

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.

59
Leave a Reply

avatar
41 Comment threads
18 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
43 Comment authors
Siderra VictorSudhakar Annadurainarendra kumarSteve CurtisTaufan Nanda Luzanil Recent comment authors

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

  Subscribe  
newest oldest most voted
Notify of
Waseem
Guest
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
Guest
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
Guest
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
Guest
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.

Hansol Lee
Guest
Hansol Lee

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

Eric
Guest
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.

Özgür
Guest
Ö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?

kinsley kajiva
Guest
kinsley kajiva

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

Clarissa Carcha
Guest
Clarissa Carcha

the php file won’t work.

trackback

[…] Android Upload file to server using PHP, MySQL […]

Oumnia Boualou
Guest
Oumnia Boualou

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

Pradipto Karmakar
Guest
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
Guest
paciopak

I have same problem. Any help?

Amshu
Guest
Amshu

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

Vamsi Tallapudi
Guest

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

Amshu
Guest
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?

Vamsi Tallapudi
Guest

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

Apurv
Guest
Apurv

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

atlasica
Guest
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
Guest
Apurv

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

f2k
Guest
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

raga vendra
Guest
raga vendra

Give permission to the app in your mobile

Sparkle Sajib
Guest

What will be the max file size?

raga vendra
Guest
raga vendra

10 mb

Harsh Malhotra
Guest
Harsh Malhotra

not able to post string along with it

sethu
Guest
sethu

Good article…was really helpful Thanks Vamsi!!

Hemanth Kumar
Guest
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
Guest
Usama Munir

Hi Sir…I have this problem…Can you plz guide me how to resolve this errorcomment image ?…i just copied your code and past it…

raga vendra
Guest
raga vendra

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

Sudhakar Annadurai
Guest
Sudhakar Annadurai

custom path means

Bliss Hu
Guest
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
Guest
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
Guest
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
comment image
SERVER: PHP 5.2 UTF-8
ANDROID: UTF-8

chamuella
Guest
chamuella

THANKS THANKS TTTTTTTHANKS!!!

Kil Kal
Guest
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
Guest
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
Guest
Syawqi Muhammad

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

Marat Kuznecsov
Guest
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);

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

Cspavithra Gowda
Guest
Cspavithra Gowda

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

Mayur Dusane
Guest
Mayur Dusane

Thanks bro. You saved my whole day. Awesome script

Rishab Surana
Guest
Rishab Surana

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

mali
Guest
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

Steve Curtis
Guest
Steve Curtis

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

ryan munene
Guest
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!

ramukaka
Guest
ramukaka

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

muhamad aminruddin
Guest
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
Guest
muhamad aminruddin

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

Sujeet Kumar
Guest
Sujeet Kumar

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

Eki Rifaldi
Guest
Eki Rifaldi

comment image

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

Steve Curtis
Guest
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

Siderra Victor
Guest
Siderra Victor

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

Cspavithra Gowda
Guest
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
Guest
Taufan Nanda Luzanil

hi sir
Thank u so much, it worked for me.
but, when i run it on my phone, the application is force close
please help…

Taufan Nanda Luzanil
Guest
Taufan Nanda Luzanil

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

narendra kumar
Guest
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
Guest
Siderra Victor

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

Siderra Victor
Guest
Siderra Victor

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

Siderra Victor
Guest
Siderra Victor

comment image

How do I solve this error?