- Android Upload File To Server Programmatically PHP-MySQL Tutorial
- Final Output Video
- PHP Scripts
- Step 1. Gradle Modifications
- Step 2. Making Permissions
- Step 3. Necessary Interface
- Step 4. Multipart related Class
- Step 5. Main Activity Works
- Reading above code
- Android Upload Image using Android Upload Service
- Android Upload Image to Server Video Tutorial
- Creating Server Side Codes for Android Upload Image
- Creating Android Studio Project
- Adding Android Upload Service
- Fetching the Uploaded Images
- Checkout these tutorials as well:
- 117 thoughts on “Android Upload Image using Android Upload Service”
Android Upload File To Server Programmatically PHP-MySQL Tutorial
Read on Android Upload File To Server Programmatically PHP-MySQL Tutorial.
I will guide you how to upload any file to php-MySQL server from android app.
We will use httpclient and multipart functionality to accomplish our goal.
A PHP script will help us to establish interaction between android app and remote server.
Final Output Video
See the following video which gives the output.
PHP Scripts
We need to create one PHP file which will help us to insert the file on to the remote server as well as MySQL database.
Make a new php file and give it a name like config.php
Write down the below source lines in config.php
Create another PHP file and its name should be uploadfile.php
Following is the code for uploadfile.php
Now our PHP related work is complete. Now in your android studio, create a new project.
Step 1. Gradle Modifications
Every android studio have two types of gradle files.
First of all, open your build.gradle(Module :app) file, you need to add below lines in this file
First two lines are integrating some classes which will allow us to use httpclient and multipart in our android project.
Last line is for dexter library. This library will help us to simplify the process of asking the runtime permissions to the user.
After this, write the following lines in build.gradle(Module :app) file
So, final code for build.gradle(Module :app) file is as the below
Now it is time to update second gradle file which have the name like build.gradle(Project: Upload_file_Zerone). In this file name Upload_file_Zerone is the name of our android studio project.
Add the below line in this file
So last source code for build.gradle(Project: Upload_file_Zerone) is like the below
Step 2. Making Permissions
In this project, we need to have three permissions from user.
Add the following source lines in AndroidManifest.xml file.
I have defined three permissions : Internet, Read external storage and Write external storage.
We also need to write runtime permissions code but I will cover them in MainActivity.java file.
Step 3. Necessary Interface
Create a new Interface and set the name as “AsyncTaskCompleteListener.java”
Source snippet for AsyncTaskCompleteListener.java is as the below
We need to implement this interface in the main activity.
Step 4. Multipart related Class
Create a new JAVA class and set its name as MultiPartRequester.java
Write down the below lines in MultiPartRequester.java
This multipart class will help us to make http calls using its objects.
We will use this class as a library, so do not change anything in this class.
Step 5. Main Activity Works
This is the final step in this tutorial.
There are two main files in this project. One is activity_main.xml and another is MainActivity.java
First, add the below code in activity_main.xml
This layout file has one button and two text views.
One text view is static and we will not change it’s value. Another text view will hold the text as the URL of the uploaded file.
When the user clicks the button, system will open the file manager.
Now following is the code block for MainActivity.java file
Reading above code
First of all, see the below source
First line is making an object of button class. Second one is for text view class.
Third line is making one string variable and its value is google URL.
Fourth one making an integer variable which defines buffer size.
Fifth line is string variable which holds the “directory” where we will save the file.
Sixth line is integer variable and last one is making one araylist of Hashmaps.
Now read the onCreate() method. It holds a method requestMultiplePermissions()
Source lines for requestMultiplePermissions() method is as the following
This method is taking care of runtime permissions stuff.
We will ask for two permissions : Read and write external storage.
Method will use dexter library to implement professional behavior regarding runtime permission environment.
Now consider the following source snippet
System will run the above code when the user clicks the button.
It will create one intent which will led the user to the new screen.
New screen will open all the files of android device and user can select any one to upload it to the server.
Now see the below source lines
When user clicks the text view, compiler will open the URL in web browser to which file is uploaded.
After selecting the file from file manager, compiler will run the onActivityResult() method.
Below is the source for onActivityResult() method.
Compiler will first get the Uri of the selected file.
Then it will store the file using getFilePathFromURI() method. This method will return the path to the saved file.
Using this path, compiler will run the uploadPDFfile() function.
Below is the source lines for uploadPDFfile() function.
Here, compiler will create one Hashmap with string as a key and value.
It will add url in first map and a path to the file in the second map.
Then it will make the http call using the MultipartRequester class.
After successful http call, compiler will run the onTaskCompleted() method.
Following is the code snippet for onTaskCompleted() method.
In this method, compiler will have a JSON response in the string format.
It will parse this JSON response and will get the URL where the uploaded file resides.
Then it will set this URL as the value of the text view.
Источник
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.
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.
- 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.
- 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.
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.
- 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.
- 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.
- 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 🙂
Hi, my name is Belal Khan and I am a Google Developers Expert (GDE) for Android. The passion of teaching made me create this blog. If you are an Android Developer, or you are learning about Android Development, then I can help you a lot with Simplified Coding.
Checkout these tutorials as well:
117 thoughts on “Android Upload Image using Android Upload Service”
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…
“Oops you just denied the permission” this message is displaying,images are not uploading,how to slove this.
Add permissions to manifest file.
If on server side check username and password.
how to check username and password on server
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’];
“Oops you just denied the permission” this toast is displaying ,images are not uploading
follow same tutorial but Error during upload occur in notification…why?
1. check that u have put tyour internet permission in manifest
2. Check that your upload url is correct
Ya, I have the same problem. Why? I have checked with the upload url and also the internet permission already.
Oops you just denied the permission how to resolve these,pls help me .
deined permission message is displaying how to slove these
nice article (y)
sir,, can i request tutorial about how to implement Single Sign-On Android??
thank u sir 🙂
Amazing tutorial guys It came exactly when I needed it to build upload for our app .. Fliiby Reply
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.
How to upload the image that is captured with camera within the android application,, im getting trouble please help….
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.
name and url are uploaded in mysql. but image is not uploading in the folder when i run the php code in postman.
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.
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.
its not able to connect the http server
getting the error on android device. File Upload Error during upload
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”
Have you found any solution?
It’s a pity … The upload is done but the pictures do not advance to the uploads folder. What should be done ?
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
you did not pass the id
I have doubts to upload the audio on server. plz help me
bas bhai aise hi kam kiya kar..osm
I am getting error while uploading …is error in upload at notification area.
Have you found any solution?
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
No longer working in Android 6.0
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/
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’];
>
?>
sorry the code went crazy. here in pastebin http://pastebin.com/MygkttBm
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
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?
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.
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
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”.
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.
hey!
i want to upload a image to asp.net server
i want to know the server side code also.
Why i am getting my image compressed?
can you give me idea?
its not the same size size i uploaded.
What if 2 or more than 2 user upload images with same name like 1.jpg then how can we differentiate in them?
Nice tutorial, one question, how do you set headers for authorization in this method?
Thanks Bro You are my saviour.
and once again thank u very very very very very very very very very very very very much
How to Upload file in Jsonobject with upload service
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
ok clear you check to commend line to write cmd and you set ipconfig/all ,
Источник