Many peoples requested me to write a tutorial to upload video to server. So in this android upload video to server tutorial we will learn how we can upload video from android gallery to our web server.
For this tutorial I will be using Hostinger’s fee web hosting server.
Some peoples also asked me about a tutorial to upload files to my website. So, you can also use this for File Upload Server Application with a little modification.
So the first thing I need to do for this android upload video to server project, is to create a php script that will handle the multipart request sent from our android device.
Creating Server Side Scripts
- Go to your hosting (You can also use wamp/xampp) and create a directory. (I created VideoUpload).
- Now inside the directory create one more directory named uploads.
- And create a new file upload.php, and write the following php code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | <?php if($_SERVER['REQUEST_METHOD']=='POST'){ $file_name = $_FILES['myFile']['name']; $file_size = $_FILES['myFile']['size']; $file_type = $_FILES['myFile']['type']; $temp_name = $_FILES['myFile']['tmp_name']; $location = "uploads/"; move_uploaded_file($temp_name, $location.$file_name); echo "http://www.simplifiedcoding.16mb.com/VideoUpload/uploads/".$file_name; }else{ echo "Error"; } |
- Note down the URL for upload.php and thats all for the server side.
Android Upload Video To Server Project
- Open android studio and create a new project. I created VideoUpload.
- Now come to activity_main.xml and write the following xml code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="net.simplifiedcoding.videoupload.MainActivity"> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Choose File" android:id="@+id/buttonChoose" /> <TextView android:id="@+id/textView" android:layout_width="match_parent" android:layout_height="wrap_content" /> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Upload" android:id="@+id/buttonUpload" /> <TextView android:id="@+id/textViewResponse" android:layout_width="match_parent" android:layout_height="wrap_content" /> </LinearLayout> |
- The above code will produce the following layout.

- Now we will create a new class to handle the upload.
- Create a new class named Upload.java and write the following code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 | package net.simplifiedcoding.videoupload; import android.util.Log; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; /** * Created by Belal on 11/22/2015. */ public class Upload { public static final String UPLOAD_URL= "http://simplifiedcoding.16mb.com/VideoUpload/upload.php"; private int serverResponseCode; public String uploadVideo(String file) { String fileName = file; HttpURLConnection conn = null; DataOutputStream dos = null; String lineEnd = "\r\n"; String twoHyphens = "--"; String boundary = "*****"; int bytesRead, bytesAvailable, bufferSize; byte[] buffer; int maxBufferSize = 1 * 1024 * 1024; File sourceFile = new File(file); if (!sourceFile.isFile()) { Log.e("Huzza", "Source File Does not exist"); return null; } try { FileInputStream fileInputStream = new FileInputStream(sourceFile); URL url = new URL(UPLOAD_URL); conn = (HttpURLConnection) url.openConnection(); conn.setDoInput(true); conn.setDoOutput(true); conn.setUseCaches(false); conn.setRequestMethod("POST"); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("ENCTYPE", "multipart/form-data"); conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); conn.setRequestProperty("myFile", fileName); dos = new DataOutputStream(conn.getOutputStream()); dos.writeBytes(twoHyphens + boundary + lineEnd); dos.writeBytes("Content-Disposition: form-data; name=\"myFile\";filename=\"" + fileName + "\"" + lineEnd); dos.writeBytes(lineEnd); bytesAvailable = fileInputStream.available(); Log.i("Huzza", "Initial .available : " + bytesAvailable); bufferSize = Math.min(bytesAvailable, maxBufferSize); buffer = new byte[bufferSize]; bytesRead = fileInputStream.read(buffer, 0, bufferSize); while (bytesRead > 0) { dos.write(buffer, 0, bufferSize); bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); bytesRead = fileInputStream.read(buffer, 0, bufferSize); } dos.writeBytes(lineEnd); dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); serverResponseCode = conn.getResponseCode(); fileInputStream.close(); dos.flush(); dos.close(); } catch (MalformedURLException ex) { ex.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } if (serverResponseCode == 200) { StringBuilder sb = new StringBuilder(); try { BufferedReader rd = new BufferedReader(new InputStreamReader(conn .getInputStream())); String line; while ((line = rd.readLine()) != null) { sb.append(line); } rd.close(); } catch (IOException ioex) { } return sb.toString(); }else { return "Could not upload"; } } } |
- The above code will simply send a multipart request to the URL specified. And will return the response from the server as a string.
- Now come to MainActivity.java and write the following code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 | package net.simplifiedcoding.videoupload; import android.app.ProgressDialog; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.os.AsyncTask; import android.provider.MediaStore; import android.support.v4.content.CursorLoader; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.Html; import android.text.method.LinkMovementMethod; import android.view.View; import android.widget.Button; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import android.widget.VideoView; import org.json.JSONException; import org.json.JSONObject; import java.io.File; public class MainActivity extends AppCompatActivity implements View.OnClickListener { private Button buttonChoose; private Button buttonUpload; private TextView textView; private TextView textViewResponse; private static final int SELECT_VIDEO = 3; private String selectedPath; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); buttonChoose = (Button) findViewById(R.id.buttonChoose); buttonUpload = (Button) findViewById(R.id.buttonUpload); textView = (TextView) findViewById(R.id.textView); textViewResponse = (TextView) findViewById(R.id.textViewResponse); buttonChoose.setOnClickListener(this); buttonUpload.setOnClickListener(this); } private void chooseVideo() { Intent intent = new Intent(); intent.setType("video/*"); intent.setAction(Intent.ACTION_GET_CONTENT); startActivityForResult(Intent.createChooser(intent, "Select a Video "), SELECT_VIDEO); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode == RESULT_OK) { if (requestCode == SELECT_VIDEO) { System.out.println("SELECT_VIDEO"); Uri selectedImageUri = data.getData(); selectedPath = getPath(selectedImageUri); textView.setText(selectedPath); } } } public String getPath(Uri uri) { Cursor cursor = getContentResolver().query(uri, null, null, null, null); cursor.moveToFirst(); String document_id = cursor.getString(0); document_id = document_id.substring(document_id.lastIndexOf(":") + 1); cursor.close(); cursor = getContentResolver().query( android.provider.MediaStore.Video.Media.EXTERNAL_CONTENT_URI, null, MediaStore.Images.Media._ID + " = ? ", new String[]{document_id}, null); cursor.moveToFirst(); String path = cursor.getString(cursor.getColumnIndex(MediaStore.Video.Media.DATA)); cursor.close(); return path; } private void uploadVideo() { class UploadVideo extends AsyncTask<Void, Void, String> { ProgressDialog uploading; @Override protected void onPreExecute() { super.onPreExecute(); uploading = ProgressDialog.show(MainActivity.this, "Uploading File", "Please wait...", false, false); } @Override protected void onPostExecute(String s) { super.onPostExecute(s); uploading.dismiss(); textViewResponse.setText(Html.fromHtml("<b>Uploaded at <a href='" + s + "'>" + s + "</a></b>")); textViewResponse.setMovementMethod(LinkMovementMethod.getInstance()); } @Override protected String doInBackground(Void... params) { Upload u = new Upload(); String msg = u.uploadVideo(selectedPath); return msg; } } UploadVideo uv = new UploadVideo(); uv.execute(); } @Override public void onClick(View v) { if (v == buttonChoose) { chooseVideo(); } if (v == buttonUpload) { uploadVideo(); } } } |
- Now add READ_EXTERNAL_STORAGE and INTERNET permission to your manifest file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="net.simplifiedcoding.videoupload"> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/> <uses-permission android:name="android.permission.INTERNET"/> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> |
- Now run your application.

- And yes it is working absolutely fine. You can get my source code from the GitHub repository. Just go to the link given below.
Get Android Upload Video to Server using PHP Source from GitHub
Some more Android Application Development Tutorial to Check
- Android RecyclerView and CardView Tutorial
- Android Volley Example to Load Image From Internet
- Android Download Image From Server
So thats all for this android upload video to server tutorial friends. I haven’t explained the code because we already have seen many tutorials like this. But still if you are having any query regarding this android upload video to server tutorial leave your comments. 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.
Hii Belal,
Thanks for this tutorial it helps me alot. it’s working absolutely fine. You are great!!
What is meant by making directory. Where should i make the directory. Im a little confused about it. Thanks in advance
Hii Belal,
I want to save video url in database with some parameter like name and address. here is the code with some change .Those changes i have made in “android-upload-video-to-server-using-php ”
public static final String KEY_TEXT = “pondid”;
public static final String KEY_TEXT1 = “name”;
public static final String UPLOAD_URL = “http://192.168.0.113/userregistration/uploads.php”;
//onCreate()
e_pondid=(EditText)findViewById(R.id.e_pondid);
e_name=(EditText)findViewById(R.id.e_name);
//uploadVideo()
final String pondid = e_pondid.getText().toString().trim();
final String name = e_name.getText().toString().trim();
//doInBackground()
RequestHandler rh = new RequestHandler();
HashMap param = new HashMap();
param.put(KEY_TEXT,pondid);
param.put(KEY_TEXT1,name);
String result = rh.sendPostRequest(UPLOAD_URL, param);
return result;
Is it working or not? You just need to store the url of the video to your mysql table. Try clubbing the other tutorial with this one..
Hii Ashwini,
I also have same doubt, I want store Video URL with some attributes like name, description.
How to send the name and address parameters from java coding.
Thanks,
i am getting a error that failed to open stream
In which line you are getting the error? Post a screenshot if you can
in line no 9 of php script.
i have mailed u screen shot on ur mail id admin@simplifiedcoding.net
as i am seeing in the screenshot you have created the PHP file inside the uploads folder
just move the script outside the uploads folder and try again
you need to change the url in android studio after moving the script
Hey Bro!
It works well after moving php script…….
Thanks………
Great Tutorial sir.
it show file uploaded successfully but i am not getting any file over the server.
tried changing permissions, but still not able to understand whats wrong in that.
Have you tried downloading my code?
Hii Belal,
It’s working and video url is getting save into database but not the id and name.
hey bro..!! i have one doubt…I have made one simple app…Which connects to server…I am accessing it through my ip…aftr some time am running that app it is not working…then i have checked my ip….it has to something else…my system ip meant…
plz do help me…
whats is happening here…that s static one…hw tat suppose changed… make it clear
I seen this situation once but never bothered about thinking why it happened. My wamp server’s ip was changing in every restart.. but now it is static and I haven’t done anything…
You have to change the ip which is working in the url
Bro, Can u please send me the Screen shot of the table created in mysql database And update the full code.. thanking you!!!
Where we have used database here? It is only sending file to server no database required here.. you can add database if you want
Dear Bilal..I just wanted to thank you for your effort you are putting to teach people stuff you worked hard to learn..
with the help of your blog i have started my own android developer job:), and it means alot since i’ll be able to bring my family from war .
thanks alot, and you will see me commenting and supporting alot:)
BTW…the best thing in your blog is that you actually reply and listen to the readers … thanks alot dude you are the best 🙂
Thanks buddy keep visiting (y)
Hello Belal
First of all, thank you for your post. I am trying to make an application which uploads a video to the server based on your code. When I try to upload a video, I get a string response successfully. But the thing is I actually do not manage to upload the file itself. I’m trying to find out what the problem is with my code, but there is a limit. So I need your help. If you don’t mind, could you visit my GitHub account and check it out?
The Android application link is https://github.com/marshallslee/VideoStreaming
The classes that are involved in uploading the videos are VideoManager.java (the class which uploads the video, link: https://github.com/marshallslee/VideoStreaming/blob/master/app/src/main/java/com/marshall/videostreaming/network/VideoManager.java) and UploadAVideoActivity.java (the UI class, link: https://github.com/marshallslee/VideoStreaming/blob/master/app/src/main/java/com/marshall/videostreaming/ui/UploadVideoActivity.java).
and the php-side link is https://github.com/marshallslee/VideoStreamingBackend/tree/master/VideoStreaming.
If you have some time to check it out and find out what the problem is, that will be very much helpful for me. Thank you in advance.
I will get back to you ASAP.. As I am having my end semester exams.. I am not able to go through your code.. So till then please keep trying (y)
Hello Belalo thanks alot for your wonderful tutorial again 🙂
Every thing you post works perfectly 🙂
Now, I have a small question,I was trying to send a String from android with the video.
In your past tutorial :
https://www.simplifiedcoding.net/android-upload-image-from-gallery-with-text/
you managed to send the text as a hashmap:
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, “UTF-8”));
writer.write(getPostDataString(postDataParams));
writer.flush();
writer.close();
I tried to implement this in this code (with the getPostDataString sure) but i failed , so i had to use this other way,
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes(“Content-Disposition: form-data; name=\”name\”” + lineEnd);
dos.writeBytes(lineEnd);
dos.writeBytes(Config.NAME); // NAMEis String variable
dos.writeBytes(lineEnd);
which is working good but i had to re do this for every string i am gonna send, I was wondering if you can tell me how to implement your old code into this one,,, (not the fully code and sure not the main activity code My problem is only with the sendpostrequest method 🙂
And i know you have exams and no hurry my friend take your time and god bless you.
Still waiting for your help master 😀
Still 😀
Bhai pahele to thank sooo much your tutorials are worth for the students like us u make it soo easy and no need to download any external library or any other stuff thnx through your tutorials I learned to post text,images on wamp and receive back thnx to u for that there is no other easy way to this except ua tutorials .. now I here with 1 problem of storing videos on server every thing is working fine just when the video is uploaded from app the response from php is ” undefined myFile” how to resolve this
php returned myFile undefined index in text view how should I resolve it
Hi man, Thank you for your posts. I was wondering, how would you use this very code to add more parameters to the data sent from upload.java to php script. I’m basically trying to upload a video with a comment at the same time.
In one of the posts where you upload to the server you did something like this;
@Override
protected String doInBackground(Void… params) {
RequestHandler rh = new RequestHandler(); already created up. But if it leads to errors use it
HashMap param = new HashMap();
param.put(Config.KEY_USR_ID, userId);
param.put(Config.KEY_CMT, cmt);
String result = rh.sendPostRequest(Config.URL, param);
return result;
}
I can’t get this to work in this particular example.
Hey man.Can you please explain me in which directory should I create php file
hi belal i want to fetch video plzzz bro help me out
Thank you for the well explained tutorials. Really nice work. This code also works for me. But I want to add the video to database. I tried to do this. Can you explain simply the way to do this? I made a android project by following your ‘upload image to server’ with some changes. I created php file too.But getting errors.i think the error comes because of php file. Please help me on this.
Hi Belal,
Thanks for your great Tutorial. I am beginner to android and for client – server Communication. My Doubt is, Can I use My Xampp Localhost IP to connect with my android, for fetching data to server and getting responses. If YES please send me the procedure. with one small example to email id(venkat.madhu03@gmail.com)…
Thanks in Advance for your help…
Hi Belal,
I am use your code for upload the mp4 file on server, it uploaded successfully but video file is not playing, so what can do for this problem.
Thanks
Hi, I’m trying to add a EditText to put a name, and add not get to send it by post with the video.
Someone can help me ?, thanks
This is real close to what I am wanting to do, however, I need a little more functionality.
Is there a way, I can make it where users have to enter their User Name and Password for the server in to the app, have it verify them on the server, then have a button to live record the video, then upload to the server, but put it in their personal video folder. I will also need to add the video to the MySql Database.
Doable?
hi Belal thi is nice tutorial to learn android , the coding was easy to learn with clear example , thank u so much belal
hi
thanks for tutorial
im worten code, uploaded file in programm , but not uploaded in my server,
please help me
Hi belal code is working at one device using Linux; U; Android 4.2.2; Build/JDQ39
but at another device Dalvik/2.1.0 (Linux; U; Android 5.1; Build/LMY47D)
it does not work.
I am sure problem is in php file.
but i am able to see some echo message come from php file to app
Kindly solve the issue thnx
Working fine, but it would be better if video is taken through camera….pls send a code to take video through device and upload it to server.
What means int maxBufferSize = 1 * 1024 * 1024?? It this work for large files?
How can I define as 30 seconds of video ? Or for example 10MB of video?
Hi,
Awesome work. How can we add a text box and put both text box value and the video URL to the mysql database?
Thank you.
The video is not getting uploaded sir!!! I have made the demo project with your github code..
video not getting upload from lolipop versions onwards…
Hi
Tnx for your article.
I try upload multi file and most of them getting this error in android :
“Caused by: java.lang.OutOfMemoryError: Failed to allocate a 65548 byte allocation with 38840 free bytes and 37KB until OOM”
Hey
Thanks a million
And it wont support the uploading of the video of greater than 1 mb
What to do?
HOW TO UPLOAD VIDEO AND STRING (LIKE Username=”john”) at same request?
How to Upload Video and String togather like(username=”John”)??
i cant download the project. can you mail it and its not working in version above lollipop
plz send tutorial Android Upload audio to Server using PHP
will u please upload tutorial uploading video using volley or retrofit
You cannot use volley for file upload
Hi BELAL KHAN
I need a help how to show video instead of video file path in your project before uploading to server.
can you please upload the tutorial for upload the audio only on local host…………….
as soon as possible
exactly i just want 2 upload my audio file so please help me??????
yes
after click button upload , i want to show in listview, but i don’t how to add thumbnail video to imageview in listview? ,can you help me ?
what to do if i want to upload my audio ?????? is there a same process for audio upload????
Hi,
i want to change the filename of the uploaded file to a custom one (read out from an edit text). I tried to pass a string with POST to the php script, but could not get it working yet.
Can u help me and show me how and at which place i have to add the code in java? I used URLEncoder.encode with UTF-8, but again, could not get it working yet.
Greetings and thanks,
Hendrik
Bilal Please tell me that upload url is working or not?
HI Bilal,
Thanks a lot for the tutorial.
Do you have a tutorial for downloading the video file ?0
hi belal thanks for the tutorial
when ı uploading the video show error mesaje “can not upload” help me
Hey great work buddy! Can you please tell me the modifications that need to done in this code if i want to upload my video to my online server?
Hi belal,
Very robust work.
It worked without single warning 🙂
Keep it up
Caused by: java.lang.SecurityException:
Permission Denial: reading com.android.providers.media.MediaProvider uri content://media/external/video/media from pid=2582, uid=10081 requires android.permission.READ_EXTERNAL_STORAGE, or grantUriPermission()
In the AndroidManifest :
I just download the projet, each time a click on a video it crash.
I do not know why always “could not upload” when using the app in my android phone. However, the video can be uploaded successfully in AVD.
Please can this be done on a remote server without android studio?
Bro can u tell where use the key and if u dont use key then please how can i did this with key because i want other field like string and image to send simultaneously
Hi,
i tried your code…………. it runs properly without any error, but there is bug. when i m selecting video file. i debug the code , it stopped on ……
private String getPath(Uri uri) { Cursor cursor = getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
how can i fix it…
thanx.
These codes do not work on version 5 of android.
selectedPath = getPath(selectedImageUri);
and
cursor.moveToFirst();
It says there are some mistakes in the parts.
Heyy Bilal,
I have tried your code it only stores the name of file on the server not the complete file. Is it from program or there is any mistake?
Thanks in advance
Hi Bilal, i am getting message, uploaed at “MY_URL”, i found nothing in my folder on the server, could you please still help out. Thanks a lot.
I want to record video and direclly store on server folder.please can you help me??
Hi Belal,
I have downloaded your code and using xampp server and running on my local machine. After clicking on upload button get below error. could you please help me fix it. thanks.
failed to connect to localhost/127.0.0.1 (port 80): connect failed: ECONNREFUSED (Connection refused)
Hi Bilal,
you are always guiding with wonderful tutorials and i used this and it is working fine. I still have few more queries, it would be great if you can help.
1. In your PHP location is uploads/, i want to keep it dynamic and send as one parameter along with video upload request. Please guide how to do it?
2. Your code worked fine on my Hostgator server but when i tried on Godaddy, no file is being uploaded. Can you guide possible fix required for Godaddy.
Hi, if i uplaod from camera folder it works but when i upload from whatsapp folder or instagram folder it gave me error.
hi ,
Its not working in marshmallow. getting path null.
I want to change uploaded video name(random). Where i change the name.
yourapp is trush firstable most important part which you didnt add download file which you share is php file and second your app doesnt upload larger files it is only 1 mb file uploaded
Thanks so much for your tutorial, please can you work on Kotlin version of this tutorial (Android Upload Video to Server using PHP), with Retrofit saving video url in database with some parameter like name , address, description.
Check this post: https://www.simplifiedcoding.net/android-upload-file-to-server/