Hello Friends, Today I will tell you file uploading in android using web service in PHP. Basically we will call web service developed in PHP using AsyncTask in android to upload file and we will get file name and file type in response.
PHP Code for Web Service
config.php
1 2 3 4 |
<?php date_default_timezone_set("Asia/Kolkata"); define("KEY", "ABCD"); //it could be anything secret key which will be shared to authorised developer only to access web service in their application define("SITE_URL","https://zatackcoder.com"); //instead of zatackcoder.com put your website url |
user.php
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 |
<?php include_once 'config.php'; header("Content-Type:application/json"); if (!isset($_REQUEST['key']) || trim($_REQUEST['key']) != KEY) { die("Not authorised"); } if (!isset($_REQUEST['action'])) { echo "Please provide action parameter"; die(); } $action = trim($_REQUEST['action']); if ($action == 'upload') { $upload_path = 'uploads/'; $upload_url = SITE_URL . '/' . $upload_path; //checking the required parameters from the request if (isset($_FILES['file']['name'])) { $fileinfo = pathinfo($_FILES['file']['name']); $extension = $fileinfo['extension']; $filename = time(); $file_url = $upload_url . $filename . '.' . $extension; //file path to upload in the server $file_path = $_SERVER["DOCUMENT_ROOT"]."/demo/api/".$upload_path . $filename . '.' . $extension; try { //saving the file if(move_uploaded_file($_FILES['file']['tmp_name'], $file_path)) { $data['fileurl'] = $file_url; $data['filetype'] = $extension; respond("200", "Uploaded successfully", $data); } } catch (Exception $e) { respond("201", $e->getMessage(), null); } } else { respond("201", 'File not selected', null); } } function respond($status, $status_message, $data) { header("HTTP/1.1 $status $status_message"); $response['status'] = $status; $response['status_message'] = $status_message; $response['data'] = $data; echo json_encode($response); } ?> |
Android Code
AndroidManifest.xml
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="com.zatackcoder.fileupload"> <uses-permission android:name="android.permission.INTERNET"/> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" 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> |
activity_main.xml
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 |
<?xml version="1.0" encoding="utf-8"?> <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.zatackcoder.fileupload.MainActivity"> <LinearLayout android:layout_width="368dp" android:layout_height="495dp" android:orientation="vertical" android:gravity="center" tools:layout_editor_absoluteY="8dp" tools:layout_editor_absoluteX="8dp" tools:ignore="MissingConstraints" android:weightSum="10"> <ImageView android:id="@+id/uploadedIV" android:layout_width="match_parent" android:layout_height="match_parent" app:srcCompat="@mipmap/ic_launcher" android:layout_weight="8" /> <TextView android:id="@+id/statusTV" android:layout_width="match_parent" android:layout_height="wrap_content" android:textAlignment="center" android:text="TextView" /> <Button android:id="@+id/uploadB" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Upload" /> </LinearLayout> </android.support.constraint.ConstraintLayout> |
FilePath.java (getting selected file path 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 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 |
package com.zatackcoder.fileupload; import android.content.ContentUris; import android.content.Context; import android.database.Cursor; import android.net.Uri; import android.os.Build; import android.os.Environment; import android.provider.DocumentsContract; import android.provider.MediaStore; /** * Created by rajesh kumar sahanee on 19/9/17. */ public class FilePath { /** * Method for return file path of Gallery image/ Document / Video / Audio * * @param context * @param uri * @return path of the selected image file from gallery */ public static String getPath(final Context context, final Uri uri) { // DocumentProvider (fot kitkat and higher version) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && DocumentsContract.isDocumentUri(context, uri)) { // ExternalStorageProvider if (isExternalStorageDocument(uri)) { final String docId = DocumentsContract.getDocumentId(uri); final String[] split = docId.split(":"); final String type = split[0]; if ("primary".equalsIgnoreCase(type)) { return Environment.getExternalStorageDirectory() + "/" + split[1]; } } // DownloadsProvider else if (isDownloadsDocument(uri)) { final String id = DocumentsContract.getDocumentId(uri); final Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(id)); return getDataColumn(context, contentUri, null, null); } // MediaProvider else if (isMediaDocument(uri)) { final String docId = DocumentsContract.getDocumentId(uri); final String[] split = docId.split(":"); final String type = split[0]; Uri contentUri = null; if ("image".equals(type)) { contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI; } else if ("video".equals(type)) { contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI; } else if ("audio".equals(type)) { contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI; } final String selection = "_id=?"; final String[] selectionArgs = new String[] { split[1] }; return getDataColumn(context, contentUri, selection, selectionArgs); } } // MediaStore (and general) else if ("content".equalsIgnoreCase(uri.getScheme())) { // Return the remote address if (isGooglePhotosUri(uri)) return uri.getLastPathSegment(); return getDataColumn(context, uri, null, null); } // File else if ("file".equalsIgnoreCase(uri.getScheme())) { return uri.getPath(); } return null; } /** * Get the value of the data column for this Uri. This is useful for * MediaStore Uris, and other file-based ContentProviders. * * @param context * The context. * @param uri * The Uri to query. * @param selection * (Optional) Filter used in the query. * @param selectionArgs * (Optional) Selection arguments used in the query. * @return The value of the _data column, which is typically a file path. */ public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) { Cursor cursor = null; final String column = "_data"; final String[] projection = { column }; try { cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null); if (cursor != null && cursor.moveToFirst()) { final int index = cursor.getColumnIndexOrThrow(column); return cursor.getString(index); } } finally { if (cursor != null) cursor.close(); } return null; } /** * @param uri * The Uri to check. * @return Whether the Uri authority is ExternalStorageProvider. */ public static boolean isExternalStorageDocument(Uri uri) { return "com.android.externalstorage.documents".equals(uri .getAuthority()); } /** * @param uri * The Uri to check. * @return Whether the Uri authority is DownloadsProvider. */ public static boolean isDownloadsDocument(Uri uri) { return "com.android.providers.downloads.documents".equals(uri .getAuthority()); } /** * @param uri * The Uri to check. * @return Whether the Uri authority is MediaProvider. */ public static boolean isMediaDocument(Uri uri) { return "com.android.providers.media.documents".equals(uri .getAuthority()); } /** * @param uri * The Uri to check. * @return Whether the Uri authority is Google Photos. */ public static boolean isGooglePhotosUri(Uri uri) { return "com.google.android.apps.photos.content".equals(uri .getAuthority()); } } |
JsonParser.java (file uploading code using post method)
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 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 |
package com.zatackcoder.fileupload; import android.util.Log; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedInputStream; 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.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.util.HashMap; /** * Created by rajesh on 19/9/17. */ public class JsonParser { String TAG = "Json Parser"; private HttpURLConnection conn; private DataOutputStream dataOutputStream; private StringBuilder result = new StringBuilder(); private JSONObject jsonObject; String lineEnd = "\r\n"; String twoHyphens = "--"; String boundary = "*****"; public JSONObject post(String url, HashMap<String, String> params, HashMap<String, String> files) { try { conn = (HttpURLConnection) new URL(url).openConnection(); conn.setDoInput(true);//Allow Inputs conn.setDoOutput(true);//Allow Outputs conn.setUseCaches(false);//Don't use a cached Copy conn.setRequestMethod("POST"); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("Accept-Charset", "UTF-8"); conn.setReadTimeout(10000); conn.setConnectTimeout(50000); if (files != null) { conn.setRequestProperty("ENCTYPE", "multipart/form-data"); conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); for (String key : files.keySet()) { conn.setRequestProperty(key, files.get(key)); } } conn.connect(); dataOutputStream = new DataOutputStream(conn.getOutputStream()); //file uploading if (files != null) { for (String key : files.keySet()) { int bytesRead, bytesAvailable, bufferSize; byte[] buffer; int maxBufferSize = 1 * 1024 * 1024; File selectedFile = new File(files.get(key)); if (!selectedFile.isFile()) { break; } dataOutputStream.writeBytes(twoHyphens + boundary + lineEnd); //writing bytes to data outputstream dataOutputStream.writeBytes("Content-Disposition: form-data; name=\"" + key + "\";filename=\"" + files.get(key) + "\"" + lineEnd); dataOutputStream.writeBytes(lineEnd); FileInputStream fileInputStream = new FileInputStream(selectedFile); //returns no. of bytes present in fileInputStream bytesAvailable = fileInputStream.available(); //selecting the buffer size as minimum of available bytes or 1 MB bufferSize = Math.min(bytesAvailable, maxBufferSize); //setting the buffer as byte array of size of bufferSize buffer = new byte[bufferSize]; //reads bytes from FileInputStream(from 0th index of buffer to buffersize) bytesRead = fileInputStream.read(buffer, 0, bufferSize); //loop repeats till bytesRead = -1, i.e., no bytes are left to read while (bytesRead > 0) { //write the bytes read from inputstream dataOutputStream.write(buffer, 0, bufferSize); bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); bytesRead = fileInputStream.read(buffer, 0, bufferSize); } dataOutputStream.writeBytes(lineEnd); dataOutputStream.writeBytes(twoHyphens + boundary + lineEnd); fileInputStream.close(); } } //parameters writing when file uploading if (params != null && files != null) { for (String key : params.keySet()) { dataOutputStream.writeBytes(twoHyphens + boundary + lineEnd); dataOutputStream.writeBytes("Content-Disposition: form-data; name=\"" + key + "\"" + lineEnd); dataOutputStream.writeBytes(lineEnd); dataOutputStream.writeBytes(params.get(key)); dataOutputStream.writeBytes(lineEnd); dataOutputStream.writeBytes(twoHyphens + boundary + lineEnd); } } //parameters writing when no file uploading else if (params != null) { StringBuilder psb = new StringBuilder(); boolean flag = false; for (String key : params.keySet()) { try { if (flag) { psb.append("&"); } psb.append(key).append("=").append(URLEncoder.encode(params.get(key), "UTF-8")); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } flag = true; } dataOutputStream.writeBytes(psb.toString()); } Log.d(TAG, "RC: " + conn.getResponseCode() + " RM: " + conn.getResponseMessage()); dataOutputStream.flush(); dataOutputStream.close(); } catch (IOException e) { e.printStackTrace(); } try { //Receive the response from the server BufferedReader reader = new BufferedReader(new InputStreamReader(new BufferedInputStream(conn.getInputStream()))); String line; while ((line = reader.readLine()) != null) { result.append(line); } Log.d(TAG, "Result: " + result.toString()); } catch (IOException e) { e.printStackTrace(); } conn.disconnect(); // try parse the string to a JSON object try { jsonObject = new JSONObject(result.toString()); } catch (JSONException e) { Log.e(TAG, "Error parsing data " + e.toString()); } // return JSON Object return jsonObject; } public JSONObject get(String url, HashMap<String, String> params) { StringBuilder psb = new StringBuilder(); boolean flag = false; for (String key : params.keySet()) { if (flag) { psb.append("&"); } try { psb.append(key).append("=").append(URLEncoder.encode(params.get(key), "UTF-8")); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } flag = true; } if (psb.length() != 0) { url += "?" + psb.toString(); Log.d(TAG, "url: " + url); } try { conn = (HttpURLConnection) new URL(url).openConnection(); conn.setDoOutput(false); conn.setRequestMethod("GET"); conn.setRequestProperty("Accept-Charset", "UTF-8"); conn.setConnectTimeout(15000); conn.connect(); } catch (IOException e) { e.printStackTrace(); } try { //Receive the response from the server BufferedReader reader = new BufferedReader(new InputStreamReader(new BufferedInputStream(conn.getInputStream()))); String line; while ((line = reader.readLine()) != null) { result.append(line); } Log.d(TAG, "Result: " + result.toString()); } catch (IOException e) { e.printStackTrace(); } conn.disconnect(); // try parse the string to a JSON object try { jsonObject = new JSONObject(result.toString()); } catch (JSONException e) { Log.e(TAG, "Error parsing data " + e.toString()); } // return JSON Object return jsonObject; } } |
Note: Here in this class I’ve created get method also but that is not used you can remove that function
MainActivity.java
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 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 |
package com.zatackcoder.fileupload; import android.Manifest; import android.app.Activity; import android.content.Intent; import android.content.pm.PackageManager; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.support.v4.app.ActivityCompat; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import org.json.JSONException; import org.json.JSONObject; import java.util.HashMap; public class MainActivity extends AppCompatActivity implements ActivityCompat.OnRequestPermissionsResultCallback { ImageView uploadedIV; TextView statusTV; Button uploadB; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); uploadedIV = (ImageView) findViewById(R.id.uploadedIV); statusTV = (TextView) findViewById(R.id.statusTV); uploadB = (Button) findViewById(R.id.uploadB); uploadB.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View view) { Intent intent = new Intent(Intent.ACTION_GET_CONTENT); intent.setType("file/*"); startActivityForResult(intent, 1); } }); getPermissions(); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if(resultCode == Activity.RESULT_OK){ if(requestCode == 1){ if(data == null){ //no data present return; } String selectedFilePath = FilePath.getPath(this, data.getData()); if(selectedFilePath != null && !selectedFilePath.equals("")){ new UploadFileAsyncTask(selectedFilePath).execute(); } else{ Toast.makeText(this,"Cannot upload file to server",Toast.LENGTH_SHORT).show(); } } } } class UploadFileAsyncTask extends AsyncTask<Void, Void, Void> { String selectedFilePath; String uploadedFilePath = ""; String fileType = ""; UploadFileAsyncTask(String selectedFilePath) { this.selectedFilePath = selectedFilePath; } @Override protected void onPreExecute() { super.onPreExecute(); statusTV.setText("Uploading..."); } @Override protected Void doInBackground(Void... voids) { HashMap params = new HashMap<String, String>(); params.put("key","ABCD"); params.put("action","upload"); HashMap fileParams = new HashMap<String, String>(); fileParams.put("file",selectedFilePath); JsonParser jsonParser = new JsonParser(); JSONObject jsonObject = jsonParser.post("https://zatackcoder.com/demo/api/user.php", params, fileParams); if(jsonObject != null) { try { JSONObject dataJson = jsonObject.getJSONObject("data"); uploadedFilePath = dataJson.getString("fileurl"); fileType = dataJson.getString("filetype"); } catch (JSONException e) { e.printStackTrace(); } } return null; } @Override protected void onPostExecute(Void aVoid) { super.onPostExecute(aVoid); statusTV.setText(uploadedFilePath); if(uploadedFilePath.isEmpty()) { statusTV.setText("Error"); } switch (fileType.toLowerCase()) { case "txt" : uploadedIV.setImageResource(R.mipmap.txt_icon); break; case "doc" : uploadedIV.setImageResource(R.mipmap.doc_icon); break; case "jpg" : uploadedIV.setImageResource(R.mipmap.jpg_icon); break; case "gif" : uploadedIV.setImageResource(R.mipmap.gif_icon); break; default: uploadedIV.setImageResource(R.mipmap.unknown_icon); } } } private void getPermissions(){ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if(checkSelfPermission(Manifest.permission.ACCESS_NETWORK_STATE) != PackageManager.PERMISSION_GRANTED || checkSelfPermission(Manifest.permission.INTERNET) != PackageManager.PERMISSION_GRANTED || checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){ //Requesting permission. ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_NETWORK_STATE, Manifest.permission.INTERNET, Manifest.permission.READ_EXTERNAL_STORAGE}, 1); } } } @Override //Override from ActivityCompat.OnRequestPermissionsResultCallback Interface public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { switch (requestCode) { case 1: { // If request is cancelled, the result arrays are empty. if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { // permission granted } return; } } } } |
Output
Android Studio Project
Please share if you like it and if you have any query you can ask in comment
Comments