Hi there, today’s lesson is about Android Upload Service. Android Upload Service is a very simple and efficient way to achieve the target of uploading files of different extensions such as .pdf, .docx, .xls and so on and use them as per required. In this example, I”ll show you how to upload pdf file to server in android. So let’s get started.
Table of Contents
Upload PDF File to Server in Android Tutorial
Setting the server for the task
- To set the server for this task, I am gonna use PHP with MySQL. So, go to localhost/phpmyadmin and a create a database as shown below. (I am using wamp server, you can use any other like xampp or even a live server as well).
- Inside your server’s root directory (c:/wamp/www) and create a new folder. I created AndroidPdfUpload.
- Inside the folder create a folder named uploads, in this folder we will save all the uploaded PDFs.
- Now, create a php file named dbDetails.php and add the following code. It stores all the constants to be used later.
1 2 3 4 5 6 | define('DB_HOST','localhost'); define('DB_USERNAME','root'); define('DB_PASSWORD',''); define('DB_NAME','YOUR_DB_NAME'); |
- Next, create another php file named upload.php and add 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 | <?php //importing dbDetails file require_once 'dbDetails.php'; //this is our upload folder $upload_path = 'uploads/'; //Getting the server ip $server_ip = gethostbyname(gethostname()); //creating the upload url $upload_url = 'http://'.$server_ip.'/AndroidPdfUpload/'.$upload_path; //response array $response = array(); if($_SERVER['REQUEST_METHOD']=='POST'){ //checking the required parameters from the request if(isset($_POST['name']) and isset($_FILES['pdf']['name'])){ //connecting to the database $con = mysqli_connect(DB_HOST,DB_USERNAME,DB_PASSWORD,DB_NAME) or die('Unable to Connect...'); //getting name from the request $name = $_POST['name']; //getting file info from the request $fileinfo = pathinfo($_FILES['pdf']['name']); //getting the file extension $extension = $fileinfo['extension']; //file url to store in the database $file_url = $upload_url . getFileName() . '.' . $extension; //file path to upload in the server $file_path = $upload_path . getFileName() . '.'. $extension; //trying to save the file in the directory try{ //saving the file move_uploaded_file($_FILES['pdf']['tmp_name'],$file_path); $sql = "INSERT INTO `notestacker`.`pdfs` (`id`, `url`, `name`) VALUES (NULL, '$file_url', '$name');"; //adding the path and name to database if(mysqli_query($con,$sql)){ //filling response array with values $response['error'] = false; $response['url'] = $file_url; $response['name'] = $name; } //if some error occurred }catch(Exception $e){ $response['error']=true; $response['message']=$e->getMessage(); } //closing the connection mysqli_close($con); }else{ $response['error']=true; $response['message']='Please choose a file'; } //displaying the response echo json_encode($response); } /* We are generating the file name so this method will return a file name for the image to be upload */ function getFileName(){ $con = mysqli_connect(DB_HOST,DB_USERNAME,DB_PASSWORD,DB_NAME) or die('Unable to Connect...'); $sql = "SELECT max(id) as id FROM pdfs"; $result = mysqli_fetch_array(mysqli_query($con,$sql)); mysqli_close($con); if($result['id']==null) return 1; else return ++$result['id']; } |
- With this, your server is all set for your android project. But before getting into android side you can test your server for file upload.
- For testing you can use any REST Client. I am using postman.

- As you can see the upload is working fine at server level. Now this is the time to code our Android Application.
Creating Android Project
- Create a new android project with Empty Activity. As the files get loaded and the gradle is built, begin with adding the dependency to the app level gradle which enables the project to use android upload service and then sync it.
1 2 3 | compile 'net.gotev:uploadservice:2.1' |
- Now, configure the MainActivity.java and activity_main.xml as shown below.
- Here’ the MainActivity.java. It consists of a method named as uploadMultipart() which carries out the upload task. It also consists of storage permissions which is required for this project as it involves reading the android storage.
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 | package chutka.bitman.com.uploadpdfsimplified; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.Manifest; import android.content.Intent; import android.content.pm.PackageManager; import android.database.Cursor; import android.graphics.Bitmap; import android.net.Uri; import android.os.Bundle; import android.provider.MediaStore; import android.support.annotation.NonNull; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.Toast; import net.gotev.uploadservice.MultipartUploadRequest; import net.gotev.uploadservice.UploadNotificationConfig; import java.io.File; import java.io.IOException; import java.io.RandomAccessFile; import java.net.URISyntaxException; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.util.UUID; public class MainActivity extends AppCompatActivity implements View.OnClickListener { //Declaring views private Button buttonChoose; private Button buttonUpload; private EditText editText; public static final String UPLOAD_URL = "http://internetfaqs.net/AndroidPdfUpload/upload.php"; //Pdf request code private int PICK_PDF_REQUEST = 1; //storage permission code private static final int STORAGE_PERMISSION_CODE = 123; //Uri to store the image uri private Uri filePath; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //Requesting storage permission requestStoragePermission(); //Initializing views buttonChoose = (Button) findViewById(R.id.buttonChoose); buttonUpload = (Button) findViewById(R.id.buttonUpload); editText = (EditText) findViewById(R.id.editTextName); //Setting clicklistener buttonChoose.setOnClickListener(this); buttonUpload.setOnClickListener(this); } /* * This is the method responsible for pdf upload * We need the full pdf path and the name for the pdf in this method * */ public void uploadMultipart() { //getting name for the image String name = editText.getText().toString().trim(); //getting the actual path of the image String path = FilePath.getPath(this, filePath); if (path == null) { Toast.makeText(this, "Please move your .pdf file to internal storage and retry", Toast.LENGTH_LONG).show(); } else { //Uploading code try { String uploadId = UUID.randomUUID().toString(); //Creating a multi part request new MultipartUploadRequest(this, uploadId, UPLOAD_URL) .addFileToUpload(path, "pdf") //Adding file .addParameter("name", name) //Adding text parameter to the request .setNotificationConfig(new UploadNotificationConfig()) .setMaxRetries(2) .startUpload(); //Starting the upload } catch (Exception exc) { Toast.makeText(this, exc.getMessage(), Toast.LENGTH_SHORT).show(); } } } //method to show file chooser private void showFileChooser() { Intent intent = new Intent(); intent.setType("application/pdf"); intent.setAction(Intent.ACTION_GET_CONTENT); startActivityForResult(Intent.createChooser(intent, "Select Pdf"), PICK_PDF_REQUEST); } //handling the image chooser activity result @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == PICK_PDF_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) { filePath = data.getData(); } } //Requesting permission private void requestStoragePermission() { if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) return; if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_EXTERNAL_STORAGE)) { //If the user has denied the permission previously your code will come to this block //Here you can explain why you need this permission //Explain here why you need this permission } //And finally ask for the permission ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, STORAGE_PERMISSION_CODE); } //This method will be called when the user will tap on allow or deny @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { //Checking the request code of our request if (requestCode == STORAGE_PERMISSION_CODE) { //If permission is granted if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { //Displaying a toast Toast.makeText(this, "Permission granted now you can read the storage", Toast.LENGTH_LONG).show(); } else { //Displaying another toast if permission is not granted Toast.makeText(this, "Oops you just denied the permission", Toast.LENGTH_LONG).show(); } } } @Override public void onClick(View v) { if (v == buttonChoose) { showFileChooser(); } if (v == buttonUpload) { uploadMultipart(); } } } |
- Here’s the activity_main.xml. It consists of few buttons and an EditText to take the input of the pdf file and filename.
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 | <?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:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" 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=".MainActivity"> <LinearLayout android:gravity="center_horizontal" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <Button android:id="@+id/buttonChoose" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Select" /> <EditText android:id="@+id/editTextName" android:hint="Name For PDF" android:layout_weight="1" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <Button android:id="@+id/buttonUpload" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Upload" /> </LinearLayout> </LinearLayout> |
- The above code will generate the following layout.
- Next, create a class named FilePath.java and add the following code. This class provides us with a method to fetch the absoulte path of the selected pdf which is required by the method uploadMultipart() in 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 158 159 160 | package chutka.bitman.com.uploadpdfsimplified; /** * Created by Manish on 10/2/2016. */ 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; public class FilePath { /** * Method for return file path of Gallery image * * @param context * @param uri * @return path of the selected image file from gallery */ public static String getPath(final Context context, final Uri uri) { //check here to KITKAT or new version final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT; // DocumentProvider if (isKitKat && 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()); } } |
- We’re almost done. Just add the Internet permission to you AndroidManifest.xml file as shown below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="chutka.bitman.com.uploadpdfsimplified"> <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> |
- And you did it. Run the app now, select the pdf and enter a name for it and the upload shall begin. The url used in this project is live. Once pdf upload is complete, its gonna flash a message saying file uploaded successfully. The sample output can be seen in the below images.

Fetching PDFs From Server
- To fetch the uploaded pdfs from the server, we need a php file to process this request. So, go ahead and create a php file named getPdfs.php and add the following code to it.
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 | <?php /** * Created by PhpStorm. * User: Manish * Date: 11/1/2016 * Time: 6:55 PM */ require_once 'dbDetails.php'; //connecting to the db $con = mysqli_connect(DB_HOST,DB_USERNAME,DB_PASSWORD,DB_NAME) or die("Unable to connect"); //sql query $sql = "SELECT * FROM `pdfs`"; //getting result on execution the sql query $result = mysqli_query($con,$sql); //response array $response = array(); $response['error'] = false; $response['message'] = "PDfs fetched successfully."; $response['pdfs'] = array(); //traversing through all the rows while($row =mysqli_fetch_array($result)){ $temp = array(); $temp['id'] = $row['id']; $temp['url'] = $row['url']; $temp['name'] = $row['name']; array_push($response['pdfs'],$temp); } echo json_encode($response); |
- With this, the server is ready to facilitate the fetching of pdfs on the app. Again you can execute this script using POSTMAN.
- As you can see we are getting the id, url and name of the uploaded pdfs in JSON format. We will read this data in android and then we will download the PDF with the URL.
- Now, let’s begin the work on the android part. To get started, begin with configuring the activity_main.xml file. To initiate the fetching of pdfs, we need a button for the same and also a listview to display the list of pdfs fetched.
- To do so, update your activity_main.xml file with the code shown below:-
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 | <?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:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" 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=".MainActivity"> <LinearLayout android:gravity="center_horizontal" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <Button android:id="@+id/buttonChoose" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Select" /> <EditText android:id="@+id/editTextName" android:hint="Name For PDF" android:layout_weight="1" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <Button android:id="@+id/buttonUpload" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Upload" /> </LinearLayout> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Fetch Pdf" android:id="@+id/buttonFetchPdf"/> <ListView android:layout_width="match_parent" android:id="@+id/listView" android:layout_height="wrap_content"> </ListView> </LinearLayout> |
- As you can see that the above xml code consists of a ListView and that calls for another layout resource file which would server as the layout of the ListView. So, go ahead and create a layout resource file named list_layout.xml and add the following code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/textViewName"/> <TextView android:layout_width="match_parent" android:layout_height="40dp" android:id="@+id/textViewUrl"/> </LinearLayout> |
- It simply consists of two TextViews to show the name and url of the fetched pdf in the ListView.
- Now that we are done with the xml part, its time to configure the Java section of this project. To do so, begin with creating a java class named Pdf.java and add 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 | package chutka.bitman.com.uploadpdfsimplified; /** * Created by Manish on 11/1/2016. **/ public class Pdf { private String url; private String name; public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getName() { return name; } public void setName(String name) { this.name = name; } } |
- The above class is the model class for Pdfs and will be used to manipulate the name and url of Pdfs.
- Next, to configure the ListView, we need to define a custom adapter. So, go ahead and create a class called PdfAdapter.java and add 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 | package chutka.bitman.com.uploadpdfsimplified; import android.app.Activity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; import java.util.ArrayList; /** * Created by Manish on 11/1/2016. */ public class PdfAdapter extends ArrayAdapter<Pdf> { Activity activity; int layoutResourceId; ArrayList<Pdf> data=new ArrayList<Pdf>(); Pdf pdf; public PdfAdapter(Activity activity, int layoutResourceId, ArrayList<Pdf> data) { super(activity, layoutResourceId, data); this.activity=activity; this.layoutResourceId=layoutResourceId; this.data=data; } @Override public View getView(int position, View convertView, ViewGroup parent) { View row=convertView; PdfHolder holder=null; if(row==null) { LayoutInflater inflater=LayoutInflater.from(activity); row=inflater.inflate(layoutResourceId,parent,false); holder=new PdfHolder(); holder.textViewName= (TextView) row.findViewById(R.id.textViewName); holder.textViewUrl= (TextView) row.findViewById(R.id.textViewUrl); row.setTag(holder); } else { holder= (PdfHolder) row.getTag(); } pdf = data.get(position); holder.textViewName.setText(pdf.getName()); holder.textViewUrl.setText(pdf.getUrl()); return row; } class PdfHolder { TextView textViewName,textViewUrl; } } |
- Now, we need to configure the MainActivity.java to make the final moves. To do so, go ahead and add the following dependency to your app level gradle and then sync it.
1 2 3 | compile 'com.android.volley:volley:1.0.0' |
- The above move just enabled the use of Volley in this project which will be used in the method which would fetch the data from the server.
- Finally, update your MainActivity.java with code below.
This update includes
- Declaration of Fetch Button, Listview, ArrayList of Pdfs, ProgressDialog, PdfAdapter, url to fetch pdfs and their intializations
- Setting on click listener to Fetch Button and ListView.
- Defining the method getPdfs() which fetches the data from the server.
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 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 | package chutka.bitman.com.uploadpdfsimplified; import android.app.ProgressDialog; import android.support.annotation.StringDef; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.Manifest; import android.content.Intent; import android.content.pm.PackageManager; import android.database.Cursor; import android.graphics.Bitmap; import android.net.Uri; import android.os.Bundle; import android.provider.MediaStore; import android.support.annotation.NonNull; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.AdapterView; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.Toast; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.StringRequest; import com.android.volley.toolbox.Volley; import net.gotev.uploadservice.MultipartUploadRequest; import net.gotev.uploadservice.UploadNotificationConfig; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.UUID; public class MainActivity extends AppCompatActivity implements View.OnClickListener { //Declaring views private Button buttonChoose; private Button buttonUpload; private EditText editText; public static final String UPLOAD_URL = "http://internetfaqs.net/AndroidPdfUpload/upload.php"; public static final String PDF_FETCH_URL = "http://internetfaqs.net/AndroidPdfUpload/getPdfs.php"; ImageView imageView; //Image request code private int PICK_PDF_REQUEST = 1; //storage permission code private static final int STORAGE_PERMISSION_CODE = 123; //Uri to store the image uri private Uri filePath; //ListView to show the fetched Pdfs from the server ListView listView; //button to fetch the intiate the fetching of pdfs. Button buttonFetch; //Progress bar to check the progress of obtaining pdfs ProgressDialog progressDialog; //an array to hold the different pdf objects ArrayList<Pdf> pdfList= new ArrayList<Pdf>(); //pdf adapter PdfAdapter pdfAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //Requesting storage permission requestStoragePermission(); //Initializing views buttonChoose = (Button) findViewById(R.id.buttonChoose); buttonUpload = (Button) findViewById(R.id.buttonUpload); editText = (EditText) findViewById(R.id.editTextName); //initializing ListView listView = (ListView) findViewById(R.id.listView); //initializing buttonFetch buttonFetch = (Button) findViewById(R.id.buttonFetchPdf); //initializing progressDialog progressDialog = new ProgressDialog(this); //Setting clicklistener buttonChoose.setOnClickListener(this); buttonUpload.setOnClickListener(this); buttonFetch.setOnClickListener(this); //setting listView on item click listener listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Pdf pdf = (Pdf) parent.getItemAtPosition(position); Intent intent = new Intent(); intent.setAction(Intent.ACTION_VIEW); intent.addCategory(Intent.CATEGORY_BROWSABLE); intent.setData(Uri.parse(pdf.getUrl())); startActivity(intent); } }); } /* * This is the method responsible for pdf upload * We need the full pdf path and the name for the pdf in this method * */ public void uploadMultipart() { //getting name for the pdf String name = editText.getText().toString().trim(); //getting the actual path of the pdf String path = FilePath.getPath(this, filePath); if (path == null) { Toast.makeText(this, "Please move your .pdf file to internal storage and retry", Toast.LENGTH_LONG).show(); } else { //Uploading code try { String uploadId = UUID.randomUUID().toString(); //Creating a multi part request new MultipartUploadRequest(this, uploadId, UPLOAD_URL) .addFileToUpload(path, "pdf") //Adding file .addParameter("name", name) //Adding text parameter to the request .setNotificationConfig(new UploadNotificationConfig()) .setMaxRetries(2) .startUpload(); //Starting the upload } catch (Exception exc) { Toast.makeText(this, exc.getMessage(), Toast.LENGTH_SHORT).show(); } } } //method to show file chooser private void showFileChooser() { Intent intent = new Intent(); intent.setType("application/pdf"); intent.setAction(Intent.ACTION_GET_CONTENT); startActivityForResult(Intent.createChooser(intent, "Select Pdf"), PICK_PDF_REQUEST); } //handling the ima chooser activity result @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == PICK_PDF_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) { filePath = data.getData(); } } //Requesting permission private void requestStoragePermission() { if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) return; if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_EXTERNAL_STORAGE)) { //If the user has denied the permission previously your code will come to this block //Here you can explain why you need this permission //Explain here why you need this permission } //And finally ask for the permission ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, STORAGE_PERMISSION_CODE); } //This method will be called when the user will tap on allow or deny @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { //Checking the request code of our request if (requestCode == STORAGE_PERMISSION_CODE) { //If permission is granted if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { //Displaying a toast Toast.makeText(this, "Permission granted now you can read the storage", Toast.LENGTH_LONG).show(); } else { //Displaying another toast if permission is not granted Toast.makeText(this, "Oops you just denied the permission", Toast.LENGTH_LONG).show(); } } } @Override public void onClick(View v) { if (v == buttonChoose) { showFileChooser(); } if (v == buttonUpload) { uploadMultipart(); } if(v==buttonFetch){ getPdfs(); } } private void getPdfs() { progressDialog.setMessage("Fetching Pdfs... Please Wait"); progressDialog.show(); StringRequest stringRequest = new StringRequest(Request.Method.POST, PDF_FETCH_URL, new Response.Listener<String>() { @Override public void onResponse(String response) { progressDialog.dismiss(); try { JSONObject obj = new JSONObject(response); Toast.makeText(MainActivity.this,obj.getString("message"), Toast.LENGTH_SHORT).show(); JSONArray jsonArray = obj.getJSONArray("pdfs"); for(int i=0;i<jsonArray.length();i++){ //Declaring a json object corresponding to every pdf object in our json Array JSONObject jsonObject = jsonArray.getJSONObject(i); //Declaring a Pdf object to add it to the ArrayList pdfList Pdf pdf = new Pdf(); String pdfName = jsonObject.getString("name"); String pdfUrl = jsonObject.getString("url"); pdf.setName(pdfName); pdf.setUrl(pdfUrl); pdfList.add(pdf); } pdfAdapter=new PdfAdapter(MainActivity.this,R.layout.list_layout, pdfList); listView.setAdapter(pdfAdapter); pdfAdapter.notifyDataSetChanged(); } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { } } ); RequestQueue request = Volley.newRequestQueue(this); request.add(stringRequest); } } |
- And you did it. Run the app now and hit the fetch pdf button to see the list of uploaded pdfs. When clicked on any List Item, it downloads the pdf for you. The sample output of this part of the project can be seen below.
- Now if you want the source code of this Upload PDF File to Server in Android Tutorial then you can get it from the below link.
So thats all for this Upload PDF File to Server in Android Tutorial. And if you are having any query or doubt regarding this Upload PDF File to Server in Android Tutorial meet me in comment section.
Hello, I am Manish Kumar. I am a B.Tech Student at NIT Jamshedpur. Fortunately, I find myself quite passionate about Computers and Technology. Android is my most recent Crush.
Hello,
Does the Request permission method work in Android 6? I tried this in the past and it only worked on Android 5.
Thanks
Yes, it definetly works on Android 6 as the above project has already been tested on Android 6.0.
do i need to change the kitkat wala code to implement it for lollipop or marshmallow ?
“//check here to KITKAT or new version
final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
// DocumentProvider
if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
Hai Manish
Does this only work with target api 19 and above? can it work with targer api 15?
Yes
So what code shud I write to replace this, so that I can use android marshmallow (api 15)?
//check here to KITKAT or new version
final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
// DocumentProvider
if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
sory i meant to say icecream sandwich, and not marshmallow
Did you try the above code on ice cream sandwich? If not ,then go ahead and do it. If you did, tell me the exact problem?
On kitkat, it works perfectly. But on icecream sandwich ( minSdkVersion 15) it says “could not find file at path: file:///mnt/extSdCard/myfile.pdf” – that is when I click upload.
hi Danish,
i get this popup(“no application can perform this action”) when i click on “select” to select pdf file…why? THANKS
That’s very strange coz the file explorer should have shown in tapping select pdf.
hi thanks for the tutorial . Please can you make a tutorial on writing to SD card in android 20 or 21 plus that is downloading straight to SD card and reading from SD card .. that would help a lot because its been a challenge for some of us.
Hie I am geeting an error while uploading the file like “Error During Upload” Can you help me please
Can I use this for uploading other file types (e.g image, doc, etc etc) ?
Thanks Brother,
Very nice project… help me a lot….
Can you add Download manager to this project? after fetching all files its work likes
/*** if file exists (View for Download) ***/
if(file.exists())
{
ViewFile(Path,FileName);
}
else
{
// if file not exists –> download first
DownloadToSDCard(FileServerPath,FileName);
}
i think theres a problem with upload … cause im trying but the file im uploading keep on overlaps to another file that i first upload.. i already uploaded 10files still the server has 1file … 🙁 please help me.
How can i test for rest client and postman
didn’t get you
Hello sir, What is the nem of the mysql light database and table?
Thank you so much. from two days I have an issue to upload a file can’t able to solve it. With the help of your code Its possible … U are greate
How to get json response aftr file uploading using json object plz help me to slove this one.
Manifest.permission.READ_EXTERNAL_STORAGE is showing error. MultipartUploadRequest and UploadNotificationConfig are also showing error.
I am getting the exception, W/System.err: org.json.JSONException: Value response of type java.lang.String cannot be converted to JSONObject
I am not able to fetch the pdfs.It keep on fetching.But at serverside,its working .And fetching the records.I used postman to check it.
i figured out the problem..And now its working fine with me..Thank you 🙂
I got stuck at upload.php where isset($_POST[‘name’]) and isset($_FILES[‘pdf’][‘name’] is always false when tested using Postman. Please help.
Okay I have to remove Header (I don’t know what is that) in Postman so the problem for this solved!
which header??
sir i am not able to understand what is the table name
you wrote this – i am confused between notestacker and pdfs , please help me in this
$sql = “INSERT INTO
notestacker
.pdfs
(id
,url
,name
) VALUES (NULL, ‘$file_url’, ‘$name’);”;Thanks
Sir
i am able to insert pdfs in mysql database, when i click on fetch button it displays links of the pdfs , when i click on the link to get pdfs , i get a message “THIS PDF COULD NOT BE OPEN”
please help me to retrive my pdfs
Thanks
Hi Samir , I am using the same Android code and the same Url provided . While uploading i am getting an error like “Error During Upload” Can you help me Please
Hi While uploading file i am getting an error like “Error during Upload” Can anybody help me please
I Got the same error, =\
I Solved that . The reason is URL provided by the author is not working , we need to write our own url with the same code the author has provided
i am using my own URL but getting the same error “Error During Upload”
did you solve the error
I think a lot of people got this problem “Error during Upload” someone had the same issue? could you share some tips? thank you
I Solved that . The reason is URL provided by the author is not working , we need to write our own url with the same code the author has provided
Hey can you upload the changes you made?…..That would be very helpful….I am Using Xampp
please provide the pdf upload and fetched code for download.
Hi Belal Sir,
Can you send me the apk file for this application.L am in dire need for the apk file for my college project
we are using 000webhost for server, we are using the steps as given above. the file is getting uploaded and it is showing a successfull message but in our uploads folder, the file is not present. Can you tell where should we keep the dbdetails.php and upload.php files so that we can get the output.
Sir i am getting the upload successful message but there is no such pdf in the root directory and none entry in the php database
hank you .your post early work.
upload document from sdcard show error could not find file path: storage/emulate/0/file.pdf in nougat
Hi Sir,
how to upload .doc,.docx file etc?? Please provide me the solution. Thank you..
How to upload multiple pdf file at one request?
Hii bilal ,this helps me for uploading the file to the server…………but I Reuired to run The ProgrssDialog and Dissmiss That Progress Dialog On Successful Ulopad………..
Hey could you make a tutorial or something for uploading a pdf using retrofit..
How did you use postman to test? It says please select a file. How did you choose a file?
Check this video https://www.youtube.com/watch?v=_0c0ay1570g&t=4s
I tried ..But it was coming same error .I dont know what the problem was .Thanks in advance
Hey
how can i see the response method of multipartUploadRequest class
please reply quickly.
Hi Manish,
I want to create an android application of PDF Reader that can fetch PDF files from the server (PHP and MYSQL)
Thanks
Pardeep Patel
hi.. If I want to upload file from sd card its not getting selected. It works with internal memory. If I want file from external memory what to do?
Now I am getting message like “Please move your .pdf file to internal storage and retry”
i am trying to select pdf form android emulator but i don’t get any item in emulator how can i am selecting pdf form android emulator
Hi there is a problem with wordpress
How do I change the name to utf8?
hi.i can upload files.but i cant’t fetch them.in case i get this :
“error”: false,
“message”: “PDfs fetched successfully.”,
“pdfs”: []
what is the problem?
when i want to open pdf file,i get this message:
cannot display PDF(name.pdf is of invalid format).
please help me
click fetch pdf button but does not display list of uploaded pdfs list & im also check my php file it working&disply list
plz i want to list of pdf file plz sir help me
what should i change if i want to show or download specific pdf instead of array ?
what should i change in the code ?
Sir…
How to solve this Error?? I cant Solve this error…
Program type already present: android.support.v4.app.BackStackState$1
can we download that fetching files? if no then let me know please how to download fetching file thanks
i am not using php services i used soap (.net services ) . can please explain to implement service in .net
sir,i get uploaded successfull message.but i didnt get any files in my server,..please help me
path==null so print toast “Please move your PDF file to internal storage & try again.” so please help whay this occur
Hello…what can I do if I’d like to fetch specific documents?
eg fetch WHERE ID = ?
HOW can I achieve that on android studio.
Still on this is it possible if you can make uploading and downloading tutorial with retrifit?
Thank you in advance.
startActivityForResult(Intent … deprecated in android 11, please update asap!