- Upload Files to Server using Service in Android
- Step for implementation
- 6. Write a File Provider
- 7. Finally, Open the Activity (MainActivity) add do below operation
- Android Upload File to Server with Progress using Retrofit
- Prerequisites
- Android Upload File to Server with Progress – Video
- Designing Database
- Building Image Upload API
- Android Upload File to Server with Progress
- Creating an Android Project
- Adding Dependencies
- Designing User Interface
- Choosing an Image from Androids Gallery
- Setting Up Retrofit for File Upload
- Uploading audio, video or image files from Android to server
- More Similar Posts
- 78 thoughts on “ Uploading audio, video or image files from Android to server ”
Upload Files to Server using Service in Android
In the previous blog, I have learned, File uploading to the server from an activity. Now In this article, I’m going to explain how to upload file to the server using Android Service.
In earlier, Normally We use IntentService to perform background task, it is an advanced form of background service in android. That creates a separate thread to perform background operation. But Android Oreo imposed some limitation of background execution. I have written a separate article on it you can read here. So IntentService does not work in Oreo devices and onward while app is in background . In Oreo Android introduced JobIntentService for performing background. It is the modern way of using the background service to perform background task(that run in both cases while app is foreground or background). I have written also a separate article on Working with JobIntentService also. Now we will use JobIntentService for file uploading.
Step for implementation
- Create a new class and extends JobIntentService.
- Now override the onHandleWork() methods.
- Setup Retrofit instance and Expose API file upload API
- Place file upload logic in onHandleWork()
- Create a local BroadCastReceiver() that update the result of service in activity
- Now expose enqueueWork() to start this service
- Open MainActivity and starts the JobIntentService
- We have to pass file path with Intent so write a below code for getting file from camera and intent.
- Open AndroidManifest and add followings code
Upload Files to Server using Service (Demo App)
Let’s implements above one by one.
1. Create a new class and extends JobIntentService
Create a new project with Basic Template. open app/build .gradle add the dependency
After that create a new class in named is FileUploadService and extends JobIntentService. Then override the onHandleWork() methods.
2. Setup Retrofit instance and Expose API file upload API
Create a interface named RestApiService and expose file upload API
Now create instances of Retrofit like this
3. Create a utility class named is CountingRequestBody
4.. Open the FileUploadService and do following operation
Furthermore, open the FileUploadService again and call the API likes below
- Place file upload logic in onHandleWork()
- Create a local BroadCastReceiver() that updates the result in activity
- Now expose enqueueWork() to start this service
The complete FileUploadService is looks like this
4.1 Declare service inside the Manifest
- For Pre-Oreo devices => We have to set uses permission – WAKE_LOCK permission
- For Oreo device => you have to declare android.permission.BIND_JOB_SERVICE
5. Open activity_main.xml and add below code
6. Write a File Provider
In this demo, we will capture image from camera and gallery with the help of FileProvider. I have written a separate article on capturing image from camera/gallery using FileProvider. I would like to suggest Read this article more clarity.
6.1 Go to res => xml => create a new xml file named is file_provider_path.xml and paste that code
6.2 Now open the AndroidManifest.xml and declare file provider inside the application tag
6.3 Declare storage and camera permission in manifest
7. Finally, Open the Activity (MainActivity) add do below operation
- We are using Dexter for using permission on run time. So Expose requestStoragePermission() for requesting permission
- Create methods for preparing intent for camera and gallery names is startCamera() and chooseGallery ()
- Handle callback result in onActivityResult()
- Register and UnRegister local BroadcastReceiver
Final code of Activity looks like below
I’m new in Android so If you have any queries or suggestions, feel free to ask them in the comment section below. Happy Coding 🙂
Источник
Android Upload File to Server with Progress using Retrofit
Hi everyone, “Uploading File or Image to Backend Server” this is something that we often need to do in many applications. We already learned this concept in many previous posts. But things keep changing in this tech world and old methods are obsolete now. That is why here I am with this Android Upload File to Server with Progress Tutorial.
The method we will learn in this post is fully updated and will work in all devices, including Android 10.
Prerequisites
- XAMPP Server: We will use it for the backend, and ofcourse we will be using PHP and MySQL here for the backend part. But if you are comfortable with some other tech for handling the backend you can do it. We basically just need the API that will accept a file.
- Retrofit: We will be using this networking library in our Android Project.
If you want to learn building RESTFul API, that you can use in your production application then please subscribe to my YouTube channel and comment to any video that you want a production level RESTFul API Development Tutorial.
You can also learn the basics of RESTFul API Development using SLIM3 PHP Framework from the below given link.
Now let’s move into our post. We will start by designing our database.
What we will do is we will store the uploaded image to an uploads directory in the backend server and we will store the path to that image in our MySQL database. And you should remember this thing, we don’t store files in our MySQL database, we just store path to the file in the database.
Android Upload File to Server with Progress – Video
In case you are more comfortable watching video tutorial, then you can watch the above playlist that explains complete step by step guide about Uploading File to Server with Progress.
But in case you are ok reading a written tutorial, keep reading, we will do the same thing here.
Designing Database
- We will be using a very simple table. So just open PhpMyAdmin (I hope your XAMPP Server is running) and create a database. In my case I have created a table named ImageUploader.
- Now we need to create a table where we will store the uploaded files info. Run the following SQL query to create a table named uploads.
- As you can see we have 3 columns in our table (id, path and description).
Building Image Upload API
- We have the database, now let’s build the Image Upload API. For this I have a directory named ImageUploader inside my root folder that is htdocs for xampp.
- Inside this directory we will create a file named DbConnect.php.
- The above file will make our database connection. Now let’s create the script that will handle the file upload.
- Create a file named Api.php and write the following code.
- The above code handle two cases. The first one is to upload the file and the next is to fetch the uploaded files.
If you need the source code of the PHP Scripts, then you can get it from the below given link.
So we have the APIs ready, now let’s create our Android Project.
Android Upload File to Server with Progress
Creating an Android Project
- I have created a new project named ImageUploader using an EmptyActivity. Once the project is loaded, we will add required dependencies and internet permission.
- First add internet permission in your AndroidManifest.xml, you also need to add the usesCleartextTraffic=”true”.
- Now we will add the required dependencies.
Adding Dependencies
- Open app level build.gradle file and add the following dependencies inside dependencies block.
- After adding these lines, sync the project.
Designing User Interface
- Now let’s design the UI. Open activity_main.xml and write the following xml code.
- The above XML Code will generate the following output.
Android Upload File to Server with Progress
- As you can see we have a very simple User Interface for our upload operation.
- Now we need an Image to Upload it. And we will let the user choose the image from device. So our first task here is to let the user choose the image to upload.
Choosing an Image from Androids Gallery
- First define a var inside your MainActivity.kt. This var will keep the uri of the selected image file.
- Now we will create two different function inside our MainActivity.kt. One is to choose the image that we will use now and other to upload the image.
- We will also attach the click listeners to our ImageView and Button to call the functions as you can see in the below code.
- The above code snippet you need to put inside your onCreate() function.
- Inside MainActivity.kt we will define a constant that we will use for getting the selected image.
- Now we will define the function openImageChooser() that will open the image picker, and we will also override the function onActivityResult() to get the selected image.
- As you can see inside the function onActivityResult() we are storing the uri of the image to the var that we defined at the beginning. We are also displaying the image selected in our ImageView.
Here we have the tricky part, we have the Uri of the image, but to upload the image we need the real path of it. If you have seen my last tutorial about Uploading Image with Retrofit, then here we have used a function that provides the real path from Uri. But this doesn’t work anymore in Android 10.
Nowadays, android recommends us to use the app directory for file storage. Every app has its own app-specific storage directory for file storage that is not accessible to other apps, and all files stored here are removed when we uninstall the application. And the good thing is too access this area you don’t need any permission.
So what we need to do is, we need to select the file from the gallery and make a copy of it inside the app-specific storage directory.
But before doing the above mentioned thing we will setup the Retrofit.
Setting Up Retrofit for File Upload
If you have used Retrofit earlier, you know what we need to do. First we will create an interface to define the API Calls.
Источник
Uploading audio, video or image files from Android to server
Check out the popular posts from Coderzheaven.com
In one of the previous posts I have shown one method to upload an image in android.
Here is another method to upload a media file like images,audio or video in android.
Here is the main java file that does the upload.
Here I am trying to open audio from the gallery. However you can change it to image or video according to your need.
The code for upload will not change since we change only the code for opening the gallery. We use only the path of the selected file whether it is image or video or audio to upload.
These are for downloading files from the server.
Layout
MainActivity
Fie Upload Utility
Server Side
Now the server side , the code is written in Php.
Things to keep in mind
1. Make sure your server is running.
2. Your server file path should be right.
3. Check your folder write permission in the server.
Please leave your valuable comments.
Enjoy.
Source Code
You can download Android Studio source code from here.
More Similar Posts
78 thoughts on “ Uploading audio, video or image files from Android to server ”
Hi Thanks for this tutorial..
Can you tell me how to store images in the emulator database and retrieve images from the database on to the emulator..
example: doctor list with their images on the emulator..
Waiting for your reply…
Its not good to store images in the database. instead copy it into a folder in your Sdcard or application sandbox and save the path of that file in your database.
For example if you have a number of images, copy it to drawable folder and store their names in the database and load it using that name. if you are downloading the images then download it to your application sandbox or sdcard and then load it from there.
and how to view the uploaded files on Android in the form of a gallery? how do we take it from server to Android?
@agatha:- I can’t understand the que actually. Do you want to see the uploaded files in your server in your android phone or what?
You can download the image from your server to your android device. check this post to how to download the images (https://coderzheaven.com/2011/07/how-to-download-an-image-in-android-programatically/)
Thanks for such nice tutorial. It is really help me.
Thank you very much!!
Its good thanks but when i m trying to upload a file having size more than 100KB it fails, without showing any error after some time it jumps to another file for uploading. Can you suggest me for this …
Hey…check your php.ini file and check your parameters such as ‘upload_max_filesize’, ‘post_max_size’, ‘max_input_time’, ‘max_execution_time’…once you set them up make sure you restart your apache service
Hey I tried my best to compile this code. but it gives many more errors. So can you please send me a link to download a course code to this function as soon as possible.
Thanks and Best Regards,
Shehan.
Hi thanks for your tutorial,it’s awesome
i try it in windows and it’s work
but when i try in linux it’s doesn’t work
what should i do??if trouble with folder permission i am not sure because i have modified the permission
please help me..thank you 🙂
@Baskoro :- Check what is the error message coming and paste it here.
Hi, Thanks for this valuable post. It helps me a lot. I have 2 doubts before implementing this solution in my app.
1. Will this program supports uploading files greater than 10MB
2. My PHP webserver is hosted on a shared hosting server where the PHP upload limit is defined as 2 MB. In this case will this program upload files greater than 10MB?
Answers
1. Yes
2. Yes, if Your server allows it.
I dont understand what do you mean by “if Your server allows it”. Do you mean the PHP.INI variable “post_max_size”
I checked out your code. I have a doubt.. Is this code allows user to send a very large file ie., greater than 20 MB.. Bcoz i tried many ways, i can upload 5MB of file sucessfully but wen i try to upload 20MB iam getting “OUT OF MEMORY” Exception.. Plz help
Try increasing the buffersize.
Hi,thanks for the nice post.But i have a doubt in this.After the file was written to the server it takes more than to two minutes to get the response from the server.So i want to know that does the reading of response depends upon the device internet speed?
Iam using 3G connection to upload file to the server.Will exception rise does the 3G connection disabled while uploading the video?
hi thanks for nice post.
i want to send some more parameters with the video.
how to add that parameters to this code.
like name,about the video etc can send to the service how to add parameter to this code?
I am gettng “There was an error uploading the file, please try again!” all the times. also i am not getting the name of my file from the server. Help me out.
hey Dhaval, please check your internet connection, server path and the file name variables. Also add the internet permission in the Android Manifest file.
I got it. The “\” were missing in the code above, the line:
String lineEnd = “rn”;
should be String line End = “\r\n”;
actually.
Also the line “dos.writeBytes(“Content-Disposition…”
had same issue. Placed “\”s and all set.
Thanks for you reply
Hey nice post . It worked form me please provide the code to send parameters with this file . Like if i want to send “key” with this file . Please reply ASAP
Hi,
can you help me with this. the code is correct yet i can’t upload the file. it was force close. “the application has stopped unexpectedly.please try again later. what should be the solution for this?
i got error in php file i tried to generate service in server it shows as follows( i am new to php please help me….. thank you)
Warning: fopen(uploaded_image.jpg) [function.fopen]: failed to open stream: Permission denied in /home/inspirei/public_html/bramara/upload/img.php on line 5
Warning: fclose(): supplied argument is not a valid stream resource in /home/inspirei/public_html/bramara/upload/img.php on line 7
Image upload complete. Please check your php file directory……
¦
Check your permissions in the PHP Server directory. You should set a write permission for the image to be uploaded in the server.
thx for code..but i have error like this..
Notice: Undefined index: uploads in C:\xampp\htdocs\upload_test\upload_media_test.php on line 5
what’s wrong?? please help me..thx
dos.writeBytes(“Content-Disposition: form-data; name=”uploadedfile”;filename=”” + selectedPath + “”” + lineEnd);
dos.writeBytes(lineEnd);
getting error on this lines plz help me out
What is the error? can you please paste it here.
To resolve syntax error in Vikrant post
dos.writeBytes(“Content-Disposition: form-data; name=\”uploaded_file\”;filename=\””+ selectedPath + “\”” + lineEnd);
dos.writeBytes(“Content-Disposition: form-data; name=”uploadedfile”;filename=”” + selectedPath + “”” + lineEnd);
dos.writeBytes(lineEnd);
getting error on this lines plz help me out
Error : Syntax error on Tokens, delete this tokens
dos.writeBytes(“Content-Disposition: form-data; name=’uploaded_file’;filename=’”
+ fileName + “‘” + lineEnd);
I’ve used the next line to try and handle the code error –
dos.writeBytes(“Content-Disposition: form-data; name=’uploaded_file’;filename=’”+ fileName + “‘” + lineEnd);
But now only – fileName – is being an error – anyone knows why is that?
There is a “semicolon” in between your code in param “writeBytes”…
remove that…
Can you exactly give the line because still i am getting error.
Hi i need to upload audio file to a online server and download it.
09-28 03:46:14.554: E/Debug(10081): Server Response
09-28 03:46:14.584: E/Debug(10081): Server Response Notice: Undefined index: uploadedfile in C:\xampp\htdocs\android\audio.php on line 5
09-28 03:46:14.594: E/Debug(10081): Server Response
09-28 03:46:14.604: E/Debug(10081): Server Response Notice: Undefined index: uploadedfile in C:\xampp\htdocs\android\audio.php on line 10
09-28 03:46:14.604: E/Debug(10081): Server Response
09-28 03:46:14.604: E/Debug(10081): Server Response Notice: Undefined index: uploadedfile in C:\xampp\htdocs\android\audio.php on line 12
09-28 03:46:14.604: E/Debug(10081): Server Response There was an error uploading the file, please try again!
09-28 03:46:14.614: E/Debug(10081): Server Response Notice: Undefined index: uploadedfile in C:\xampp\htdocs\android\audio.php on line 17
09-28 03:46:14.614: E/Debug(10081): Server Response filename: target_path: uploads/
same problem here
Thanks!!
Its Working. But how can i implement progress bar with calculating uploaded bytes with this Example?
Add this line before loop otherwise zero kb data is uploaded on server.
// Read file
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0)
<
System.out.println(“Inside while loop”);
outputStream.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
>
Thanks for the information.
Hi very nice post. But this code failed when uploading file size greater than 20MB i.e it throws exception OutOfMemory. How do I increase the buffer size? or any other way to resolve this.
should we follow these ” How to create a new Virtual SD card in emulator in ANDROID? How to start emulator with the created SDCard?” and “How to add files like images inside your emulator in ANDROID?” tutorials to open the emulator? thanks
I always get 03-15 19:48:59.414: E/Debug(32243): Server Response There was an error uploading the file, please try again!filename: target_path: Upload/
Why? When I am running your code, filename is known but it looks like it is not forwarded with the code
Did you check the file path? it is correct?
Did you check for null before uploading the file?
Nice post. Thanks a lot for these genius posts.
Hi I have tried your code for client and server both, and I am getting below response
Server Response There was an error uploading the file, please try again!filename: target_path: upload/
Please help me out ..how to solve this and what is the issue ?
Did you check your server folder permission where you are uploading the file.
getting same error… and gave permissions of server folder also
Try uploading the image to the server folder from a Client like Filezilla. It should work with the above code.
this code not works on android kitkat any solution?
Hy, I want to upload large file About 50MB, but I was got error of out of memory.
I convert video file in to bytearray then is getting error.
I upload video like this. record video and then convert in bytearry for encode base64 and getting string value from encoding file and post data in to our server.
please have a solution of that issue then help me. Thank you in advance.
i got error, Error converting result java.io.IOException: Attempted read on closed stream.
My LOG cant show before dos = new DataOutputStream(conn.getOutputStream());
hllo sr where we place php code in android??
tell me
I want to upload image, video and audio together. How can i do that with this code ?
/* Add the original filename to our target path.
Result is “uploads/filename.extension” */
$target_path = $target_path . basename( $_FILES[‘uploadedfile’][‘name’]);
i m not getting that what would be the uploadedfile name bcos user can select any file from gallery
uploadedfile is the one selected by the user from the gallery.
how to Handle Breakdown while uploading and how to Resumable uploading like google play store in android.
For resuming you server should support it.
No get any response from server
shailesh,
What error are you getting?
php codeignator not work pls help
Hello, Running this code, I am getting: HTTP Response: Bad Gateway 502.
How can i resolve this issue?
Kayode, It would be better to check your server.
“The server was acting as a gateway or proxy and received an invalid response from the upstream server.” There are many other 5xx server error messages, all of which boil down to: “The server failed to fulfill an apparently valid request.”
is it work of pdf and doc files also
It will work on any file, but depends on the server side code.
cannot resolve symbol uploadfile?
dos.writeBytes(“Content-Disposition: form-data; name=”uploadedfile”;filename=”” + selectedPath + “”” + lineEnd);
cannot resolve symbol uploadfile?
how resolve it?
use ( \ ) before ( each ” )
Thanks For tutorial, but now I Want to upload image with some parameters like name,Description to save mysql database from where i can pass these parameters??
Источник