Android Upload file to server using PHP, MySQL

61
5219
Android Upload File to Server

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.

Related links

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

0 0 vote
Article Rating
Subscribe
Notify of
guest

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

61 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Waseem
Waseem
4 years ago

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
chirag gandhi
4 years ago

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
Hansol Lee
4 years ago

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
Omaima Tauqeer
4 years ago
Reply to  Hansol Lee

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
Hansol Lee
4 years ago
Reply to  Omaima Tauqeer

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

Eric
Eric
4 years ago

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
Özgür
4 years ago

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
kinsley kajiva
3 years ago
Reply to  Özgür

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

Clarissa Carcha
Clarissa Carcha
4 years ago

the php file won’t work.

trackback

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

Oumnia Boualou
Oumnia Boualou
4 years ago

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

Pradipto Karmakar
Pradipto Karmakar
4 years ago

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
paciopak
4 years ago

I have same problem. Any help?

Amshu
Amshu
3 years ago

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

Vamsi Tallapudi
3 years ago
Reply to  Amshu

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

Amshu
Amshu
3 years ago

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
3 years ago

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

Apurv
Apurv
4 years ago

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

atlasica
atlasica
4 years ago

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
Apurv
4 years ago

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

f2k
f2k
3 years ago

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
raga vendra
3 years ago
Reply to  f2k

Give permission to the app in your mobile

Sparkle Sajib
3 years ago

What will be the max file size?

raga vendra
raga vendra
3 years ago
Reply to  Sparkle Sajib

10 mb

Harsh Malhotra
Harsh Malhotra
3 years ago

not able to post string along with it

sethu
sethu
3 years ago

Good article…was really helpful Thanks Vamsi!!

Hemanth Kumar
Hemanth Kumar
3 years ago

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
Usama Munir
3 years ago

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
raga vendra
3 years ago
Reply to  Usama Munir

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

Sudhakar Annadurai
Sudhakar Annadurai
2 years ago
Reply to  raga vendra

custom path means

Bliss Hu
Bliss Hu
3 years ago

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
Sam Boychuk
3 years ago

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
chamuella
3 years ago

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
chamuella
3 years ago

THANKS THANKS TTTTTTTHANKS!!!

Kil Kal
Kil Kal
3 years ago

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
Gamal Sebaee
3 years ago

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
Syawqi Muhammad
3 years ago

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

Marat Kuznecsov
Marat Kuznecsov
3 years ago

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=””+… Read more »

Cspavithra Gowda
Cspavithra Gowda
3 years ago

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

Mayur Dusane
Mayur Dusane
3 years ago

Thanks bro. You saved my whole day. Awesome script

Rishab Surana
Rishab Surana
3 years ago

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

mali
mali
3 years ago

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
Steve Curtis
3 years ago
Reply to  mali

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

ryan munene
ryan munene
3 years ago

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
ramukaka
3 years ago

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

muhamad aminruddin
muhamad aminruddin
3 years ago

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

muhamad aminruddin
muhamad aminruddin
3 years ago

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

Sujeet Kumar
Sujeet Kumar
3 years ago

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

Eki Rifaldi
Eki Rifaldi
3 years ago

comment image

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

Steve Curtis
Steve Curtis
3 years ago
Reply to  Eki Rifaldi

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
Siderra Victor
2 years ago
Reply to  Steve Curtis

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

Cspavithra Gowda
Cspavithra Gowda
3 years ago

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
Taufan Nanda Luzanil
3 years ago

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
Taufan Nanda Luzanil
3 years ago

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

narendra kumar
narendra kumar
2 years ago

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
Siderra Victor
2 years ago
Reply to  narendra kumar

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

Siderra Victor
Siderra Victor
2 years ago

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

Siderra Victor
Siderra Victor
2 years ago

comment image

How do I solve this error?

sanket
sanket
5 months ago

sir how to place file to pHp server