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
[sociallocker id=1372]Android Upload Video To Server[/sociallocker]
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 🙂