How to Upload a Pdf to a Server

Our this tutorial Android Upload PDF File to Server is very accelerate tutorial for android developers because we have uploading PDF file direct to online website hosting server by using PHP script. Later on sending the file directly to sever we would receive that file using POST method and store that file on a folder created on domain server. Nosotros would also store the complete uploaded PDF path URL into MySQL database. So it could exist accessed for some farther usages.

Contents in this project Android Upload PDF File to Server Using PHP MySQL :

  1. Spotter the live demo video.
  2. Start a new android application development project in Studio.
  3. Create Database with Tabular array on server.
  4. Create PDF storage folder on server.
  5. Create PHP Script to receive PDF file coming from awarding.
  6. Addingnet.gotev:uploadservice:2.one library in your project.
  7. Calculation Internet and READ_EXTERNAL_STORAGE permission to AndroidManifest.xml file.
  8. Create Two buttons and one EditText in layout file.
  9. Starting time Coding.

Listing of Java files in this project :

  • MainActivity.coffee .
  • FilePath.java .

Listing of Layout file in this projection :

  • activity_main.xml .

List of PHP file in this projection :

  • file_upload.php .

1. Watch the live demo video :

2. Get-go a new android awarding development project in Studio.

3. Create Database with Table on server :

Create Database on your hosting or local sever and within that database create a tabular array named equally " PdfTable ". Inside that table create 3 columns id, PdfURL, PdfName . Screenshot of tabular array is given below.

4. Create PDF storage folder on server :

My testing domain proper noun isandroidblog.esy.es . I am creating a folder inside my domain hosting storage and inside that folder my PDF uploading folder present. My PDF uploading binder path ishttp://androidblog.esy.es/AndroidJSon/PdfUploadFolder/ . So merely create same binder with same name on your server.

5. Create PHP Script to receive PDF file coming from application :

Next step is to create the PHP scripting file which URL we would call from application and this file would store PDF on server.
Code for file_upload.php file.

<?php   ServerConfig();  $PdfUploadFolder = 'PdfUploadFolder/';   $ServerURL = 'http://androidblog.esy.es/AndroidJSon/'.$PdfUploadFolder;   if($_SERVER['REQUEST_METHOD']=='POST'){    if(isset($_POST['proper name']) and isset($_FILES['pdf']['name'])){   $con = mysqli_connect(HostName,HostUser,HostPass,DatabaseName);    $PdfName = $_POST['name'];    $PdfInfo = pathinfo($_FILES['pdf']['name']);    $PdfFileExtension = $PdfInfo['extension'];    $PdfFileURL = $ServerURL . GenerateFileNameUsingID() . '.' . $PdfFileExtension;    $PdfFileFinalPath = $PdfUploadFolder . GenerateFileNameUsingID() . '.'. $PdfFileExtension;    try{    move_uploaded_file($_FILES['pdf']['tmp_name'],$PdfFileFinalPath);    $InsertTableSQLQuery = "INSERT INTO PdfTable (PdfURL, PdfName) VALUES ('$PdfFileURL', '$PdfName') ;";   mysqli_query($con,$InsertTableSQLQuery);   }grab(Exception $e){}   mysqli_close($con);    } }  function ServerConfig(){   define('HostName','mysql.hostinger.in'); define('HostUser','u288012116_json'); define('HostPass','N1c45hlf'); ascertain('DatabaseName','u288012116_json');   }  office GenerateFileNameUsingID(){    $con2 = mysqli_connect(HostName,HostUser,HostPass,DatabaseName);    $GenerateFileSQL = "SELECT max(id) as id FROM PdfTable";    $Holder = mysqli_fetch_array(mysqli_query($con2,$GenerateFileSQL));   mysqli_close($con2);    if($Holder['id']==null)  {  return 1;  }  else  {  return ++$Holder['id'];  } }  ?>

six. Adding net.gotev:uploadservice:2.1 library in your project :

ane. Open your projection'sbuild.gradle(Module:app) file.

2. Add compile 'internet.gotev:uploadservice:ii.ane' independencies scope .

net.gotev:uploadservice:2.1'

7. Adding Internet and READ_EXTERNAL_STORAGE permission to AndroidManifest.xml file :

Open your project'due south AndroidManifest.xml file and add beneath both permission inside it. Y'all could observe the complete AndroidManifest.xml file source code at the end of this page.

 <uses-permission android:name="android.permission.Internet"/>  <uses-permission android:proper name="android.permission.READ_EXTERNAL_STORAGE"/>

 8. Create Two buttons and one EditText in layout file :

<EditText     android:layout_width="fill_parent"     android:layout_height="wrap_content"     android:inputType="textPersonName"     android:hint="Enter PDF Name"     android:ems="10"     android:gravity="center"     android:layout_centerVertical="truthful"     android:layout_centerHorizontal="true"     android:id="@+id/editText" />  <Button     android:text="Upload pdf on online server"     android:layout_width="fill_parent"     android:layout_height="wrap_content"     android:layout_marginTop="54dp"     android:id="@+id/button2"     android:layout_below="@+id/editText"     android:layout_alignParentStart="true" />  <Button     android:text="Select PDF TO Upload"     android:layout_width="fill_parent"     android:layout_height="wrap_content"     android:id="@+id/button"     android:layout_above="@+id/editText"     android:layout_alignParentStart="true"     android:layout_marginBottom="62dp" />

 9. Start Coding for project Android Upload PDF File to Server :

Code for MainActivity.java file.

package com.androidjson.pdfuploadandroid_androidjsoncom; import android.back up.v7.app.AppCompatActivity; import android.os.Bundle; import android.Manifest; import android.content.Intent; import android.content.pm.PackageManager; import android.net.Uri; import android.support.v4.app.ActivityCompat; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import internet.gotev.uploadservice.MultipartUploadRequest; import net.gotev.uploadservice.UploadNotificationConfig; import java.util.UUID;  public class MainActivity extends AppCompatActivity{      Button SelectButton, UploadButton;      EditText PdfNameEditText ;      Uri uri;      public static concluding String PDF_UPLOAD_HTTP_URL = "http://androidblog.esy.es/AndroidJSon/file_upload.php";      public int PDF_REQ_CODE = one;      Cord PdfNameHolder, PdfPathHolder, PdfID;      @Override     protected void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.activity_main);          AllowRunTimePermission();          SelectButton = (Push) findViewById(R.id.button);         UploadButton = (Push button) findViewById(R.id.button2);         PdfNameEditText = (EditText) findViewById(R.id.editText);          SelectButton.setOnClickListener(new View.OnClickListener() {             @Override             public void onClick(View view) {                  // PDF selection code start from here .                  Intent intent = new Intent();                  intent.setType("application/pdf");                  intent.setAction(Intent.ACTION_GET_CONTENT);                  startActivityForResult(Intent.createChooser(intent, "Select Pdf"), PDF_REQ_CODE);              }         });          UploadButton.setOnClickListener(new View.OnClickListener() {             @Override             public void onClick(View view) {                  PdfUploadFunction();              }         });      }      @Override     protected void onActivityResult(int requestCode, int resultCode, Intent data) {         super.onActivityResult(requestCode, resultCode, data);          if (requestCode == PDF_REQ_CODE && resultCode == RESULT_OK && information != zilch && data.getData() != null) {              uri = data.getData();              SelectButton.setText("PDF is Selected");         }     }      public void PdfUploadFunction() {          PdfNameHolder = PdfNameEditText.getText().toString().trim();          PdfPathHolder = FilePath.getPath(this, uri);          if (PdfPathHolder == nix) {              Toast.makeText(this, "Please move your PDF file to internal storage & try again.", Toast.LENGTH_LONG).show();          } else {              endeavor {                  PdfID = UUID.randomUUID().toString();                  new MultipartUploadRequest(this, PdfID, PDF_UPLOAD_HTTP_URL)                         .addFileToUpload(PdfPathHolder, "pdf")                         .addParameter("name", PdfNameHolder)                         .setNotificationConfig(new UploadNotificationConfig())                         .setMaxRetries(5)                         .startUpload();              } catch (Exception exception) {                  Toast.makeText(this, exception.getMessage(), Toast.LENGTH_SHORT).show();             }         }     }       public void AllowRunTimePermission(){          if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE))         {              Toast.makeText(MainActivity.this,"READ_EXTERNAL_STORAGE permission Admission Dialog", Toast.LENGTH_LONG).show();          } else {              ActivityCompat.requestPermissions(MainActivity.this,new Cord[]{ Manifest.permission.READ_EXTERNAL_STORAGE}, 1);          }     }      @Override     public void onRequestPermissionsResult(int RC, String per[], int[] Result) {          switch (RC) {              case i:                  if (Result.length > 0 && Outcome[0] == PackageManager.PERMISSION_GRANTED) {                      Toast.makeText(MainActivity.this,"Permission Granted", Toast.LENGTH_LONG).show();                  } else {                      Toast.makeText(MainActivity.this,"Permission Canceled", Toast.LENGTH_LONG).evidence();                  }                 break;         }     }   }

Code for activity_main.xml layout file.

<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"     xmlns:tools="http://schemas.android.com/tools"     android:id="@+id/activity_main"     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="com.androidjson.pdfuploadandroid_androidjsoncom.MainActivity">      <EditText         android:layout_width="fill_parent"         android:layout_height="wrap_content"         android:inputType="textPersonName"         android:hint="Enter PDF Name"         android:ems="10"         android:gravity="center"         android:layout_centerVertical="true"         android:layout_centerHorizontal="truthful"         android:id="@+id/editText" />      <Push button         android:text="Upload pdf on online server"         android:layout_width="fill_parent"         android:layout_height="wrap_content"         android:layout_marginTop="54dp"         android:id="@+id/button2"         android:layout_below="@+id/editText"         android:layout_alignParentStart="true" />      <Button         android:text="Select PDF TO Upload"         android:layout_width="fill_parent"         android:layout_height="wrap_content"         android:id="@+id/button"         android:layout_above="@+id/editText"         android:layout_alignParentStart="true"         android:layout_marginBottom="62dp" />   </RelativeLayout>

Code for FilePath.java file.

package com.androidjson.pdfuploadandroid_androidjsoncom;  /**  * Created past Juned on one/17/2017.  */  import android.content.ContentUris; import android.content.Context; import android.database.Cursor; import android.internet.Uri; import android.os.Build; import android.os.Surround; import android.provider.DocumentsContract; import android.provider.MediaStore;  public grade FilePath {     /**      * Method for return file path of Gallery image      *      * @param context      * @param uri      * @return path of the selected paradigm file from gallery      */      public static String getPath(final Context context, terminal Uri uri)     {         //bank 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 Cord docId = DocumentsContract.getDocumentId(uri);                 concluding String[] split = docId.divide(":");                 final String type = split[0];                  if ("primary".equalsIgnoreCase(type)) {                     return Environment.getExternalStorageDirectory() + "/" + split[ane];                 }             }              //DownloadsProvider             else if (isDownloadsDocument(uri)) {                  final Cord 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 blazon = split[0];                  Uri contentUri = aught;                 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 Cord selection = "_id=?";                 terminal String[] selectionArgs = new Cord[] {                         separate[1]                 };                  render 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();         }          render 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) Option arguments used in the query.      * @return The value of the _data column, which is typically a file path.      */     public static Cord getDataColumn(Context context, Uri uri, String selection,                                        Cord[] selectionArgs) {          Cursor cursor = nothing;         terminal Cord column = "_data";         final String[] projection = {                 column         };          try {             cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,                     cypher);             if (cursor != zero && cursor.moveToFirst()) {                 final int index = cursor.getColumnIndexOrThrow(column);                 return cursor.getString(index);             }         } finally {             if (cursor != null)                 cursor.shut();         }         return null;     }      /**      * @param uri The Uri to bank 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 cheque.      * @return Whether the Uri authorisation is DownloadsProvider.      */     public static boolean isDownloadsDocument(Uri uri) {         return "com.android.providers.downloads.documents".equals(uri.getAuthority());     }      /**      * @param uri The Uri to cheque.      * @render Whether the Uri potency 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());     } }

Lawmaking for AndroidManifest.xml file.

<?xml version="1.0" encoding="utf-eight"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android"     package="com.androidjson.pdfuploadandroid_androidjsoncom">      <uses-permission android:proper name="android.permission.INTERNET"/>     <uses-permission android:proper name="android.permission.READ_EXTERNAL_STORAGE"/>      <application         android:allowBackup="true"         android:icon="@mipmap/ic_launcher"         android:label="@string/app_name"         android:supportsRtl="truthful"         android:theme="@fashion/AppTheme">         <action android:name=".MainActivity">             <intent-filter>                 <activeness android:proper noun="android.intent.activeness.MAIN" />                  <category android:name="android.intent.category.LAUNCHER" />             </intent-filter>         </activity>     </awarding>  </manifest>

Lawmaking for PHP File :

Code for file_upload.php file.

<?php   ServerConfig();  $PdfUploadFolder = 'PdfUploadFolder/';   $ServerURL = 'http://androidblog.esy.es/AndroidJSon/'.$PdfUploadFolder;   if($_SERVER['REQUEST_METHOD']=='POST'){    if(isset($_POST['proper name']) and isset($_FILES['pdf']['name'])){   $con = mysqli_connect(HostName,HostUser,HostPass,DatabaseName);    $PdfName = $_POST['name'];    $PdfInfo = pathinfo($_FILES['pdf']['name']);    $PdfFileExtension = $PdfInfo['extension'];    $PdfFileURL = $ServerURL . GenerateFileNameUsingID() . '.' . $PdfFileExtension;    $PdfFileFinalPath = $PdfUploadFolder . GenerateFileNameUsingID() . '.'. $PdfFileExtension;    endeavour{    move_uploaded_file($_FILES['pdf']['tmp_name'],$PdfFileFinalPath);    $InsertTableSQLQuery = "INSERT INTO PdfTable (PdfURL, PdfName) VALUES ('$PdfFileURL', '$PdfName') ;";   mysqli_query($con,$InsertTableSQLQuery);   }catch(Exception $due east){}   mysqli_close($con);    } }  part ServerConfig(){   define('HostName','mysql.hostinger.in'); define('HostUser','u288012116_json'); define('HostPass','N1c45hlf'); define('DatabaseName','u288012116_json');   }  part GenerateFileNameUsingID(){    $con2 = mysqli_connect(HostName,HostUser,HostPass,DatabaseName);    $GenerateFileSQL = "SELECT max(id) every bit id FROM PdfTable";    $Holder = mysqli_fetch_array(mysqli_query($con2,$GenerateFileSQL));   mysqli_close($con2);    if($Holder['id']==null)  {  render 1;  }  else  {  render ++$Holder['id'];  } }  ?>

Screenshot :

Android Upload PDF File to Server

Download Code

johnsonsqualoodding93.blogspot.com

Source: https://androidjson.com/android-upload-pdf-file-server-php-mysql/

0 Response to "How to Upload a Pdf to a Server"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel