How to Upload File to Google Drive in Js

Laravel PHP Create Folder and Upload file to google drive with access token

Laravel PHP Create Folder and Upload file to google drive with access token

In this Laravel PHP tutorial, I will tell you how to upload file on Google drive using Google drive API.

I have already discussed about Login hallmark with Google APIs, Y'all can follow this link to get admission token after successfully hallmark with Google OAuth2 API.

For this case, I need refresh token for permanent access to Google APIs considering Admission token accept express lifetime that ways you will have to repeat the OAuth 2.0 consent flow to authenticate user, but If you have refresh token and then y'all can employ this refresh token to obtain a new access token.

At the time of initial dominance request but, Google provide refresh token but to obtain refresh token you lot will have to specify offline access like this :

$this->gClient->setAccessType("offline"); $this->gClient->setApprovalPrompt("forcefulness");          

Y'all will accept to enable Google Drive API with your Google account.

You demand to take client_id, client_secret and api_key for this example.

Step 1 : Installation

First I volition go with fresh installation by running following command :

composer create-project --prefer-dist laravel/laravel blog "v.4.*"          
Step ii : User Table

Now I volition create User tabular array to store token after authentication with Google for time to come admission.

When you install fresh Laravel awarding then you volition accept migration file for users table by default in following path database/migrations.

Now add together a column "access_token" in users migration file to save access token for each user afterward authentication with Google APIs.

              
  1. public function upwardly ()
  2. {
  3. Schema:: create ( 'users' , function (Blueprint $table ) {
  4. $table -> increments ( 'id' );
  5. $table -> string ( 'name' );
  6. $tabular array -> cord ( 'email' )-> unique ();
  7. $table -> string ( 'password' );
  8. $table -> text ( 'access_token' );
  9. $table -> rememberToken ();
  10. $tabular array -> timestamps ();
  11. } );
  12. }
public office up()     {         Schema::create('users', function (Blueprint $table) {             $table->increments('id');             $table->string('name');             $table->string('email')->unique();             $table->string('countersign');             $table->text('access_token');             $tabular array->rememberToken();             $table->timestamps();         });     }

Put above code in users migration file and run following command to create table in your database :

php artisan migrate
Pace iii : Install Google Client Library

In this step, I will install the Google Client library by using composer, Add together following line in your composer.json file :

"crave": { 	.... 	"google/apiclient": "2.0.*" }          

Now update your composer by running following command :

composer update          
Step 4 : Add Routes

Now we will add together some routes for this example :

routes/web.php
Route::become('glogin',assortment('as'=>'glogin','uses'=>'UserController@googleLogin')) ; Route::mail('upload-file',array('as'=>'upload-file','uses'=>'UserController@uploadFileUsingAccessToken')) ;          
Pace 5 : User Controller

In this UserController, We accept ii method with constructor. In constructor, I will define the authorized Google customer object.

googleLogin() method is used to cosign user and save access token of that user in a "users" table.

uploadFileUsingAccessToken() method is used to upload file to user's google drive account but before uploading files or creating folder, We will check if access token is expired then generate new one with the aid of refresh token.

              
  1. <?php
  2. namespace App\Http\Controllers;
  3. use Illuminate\Http\Request;
  4. apply App\Http\Controllers\Controller;
  5. use App\User;
  6. grade UserController extends Controller
  7. {
  8. public $gClient ;
  9. public function __construct () {
  10. $google_redirect_url = route ( 'glogin' );
  11. $this ->gClient = new \ Google_Client ();
  12. $this ->gClient-> setApplicationName ( config ( 'services.google.app_name' ));
  13. $this ->gClient-> setClientId ( config ( 'services.google.client_id' ));
  14. $this ->gClient-> setClientSecret ( config ( 'services.google.client_secret' ));
  15. $this ->gClient-> setRedirectUri ( $google_redirect_url );
  16. $this ->gClient-> setDeveloperKey ( config ( 'services.google.api_key' ));
  17. $this ->gClient-> setScopes ( array (
  18. 'https://www.googleapis.com/auth/drive.file' ,
  19. 'https://www.googleapis.com/auth/bulldoze'
  20. ));
  21. $this ->gClient-> setAccessType ( "offline" );
  22. $this ->gClient-> setApprovalPrompt ( "force" );
  23. }
  24. public function googleLogin (Asking $request ) {
  25. $google_oauthV2 = new \ Google_Service_Oauth2 ( $this ->gClient);
  26. if ( $request -> get ( 'code' )) {
  27. $this ->gClient-> authenticate ( $asking -> become ( 'lawmaking' ));
  28. $asking -> session ()-> put ( 'token' , $this ->gClient-> getAccessToken ());
  29. }
  30. if ( $request -> session ()-> go ( 'token' ))
  31. {
  32. $this ->gClient-> setAccessToken ( $request -> session ()-> become ( 'token' ));
  33. }
  34. if ( $this ->gClient-> getAccessToken ())
  35. {
  36. $user =User:: find ( 1 );
  37. $user ->access_token= json_encode ( $asking -> session ()-> get ( 'token' ));
  38. $user -> save ();
  39. dd ( "Successfully authenticated" );
  40. } else
  41. {
  42. $authUrl = $this ->gClient-> createAuthUrl ();
  43. return redirect ()-> to ( $authUrl );
  44. }
  45. }
  46. public function uploadFileUsingAccessToken () {
  47. $service = new \ Google_Service_Drive ( $this ->gClient);
  48. $user =User:: find ( 1 );
  49. $this ->gClient-> setAccessToken ( json_decode ( $user ->access_token,true));
  50. if ( $this ->gClient-> isAccessTokenExpired ()) {
  51. $refreshTokenSaved = $this ->gClient-> getRefreshToken ();
  52. $this ->gClient-> fetchAccessTokenWithRefreshToken ( $refreshTokenSaved );
  53. $updatedAccessToken = $this ->gClient-> getAccessToken ();
  54. $updatedAccessToken [ 'refresh_token' ] = $refreshTokenSaved ;
  55. $this ->gClient-> setAccessToken ( $updatedAccessToken );
  56. $user ->access_token= $updatedAccessToken ;
  57. $user -> save ();
  58. }
  59. $fileMetadata = new \ Google_Service_Drive_DriveFile ( array (
  60. 'name' => 'ExpertPHP' ,
  61. 'mimeType' => 'application/vnd.google-apps.folder' ));
  62. $binder = $service ->files-> create ( $fileMetadata , array (
  63. 'fields' => 'id' ));
  64. printf ( "Folder ID: %southward\due north" , $folder ->id);
  65. $file = new \ Google_Service_Drive_DriveFile ( array (
  66. 'name' => 'cdrfile.jpg' ,
  67. 'parents' => array ( $folder ->id)
  68. ));
  69. $event = $service ->files-> create ( $file , array (
  70. 'data' => file_get_contents ( public_path ( 'images/myimage.jpg' )),
  71. 'mimeType' => 'application/octet-stream' ,
  72. 'uploadType' => 'media'
  73. ));
  74. $url = 'https://drive.google.com/open?id=' . $result ->id;
  75. dd ( $result );
  76. }
  77. }
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; utilize App\Http\Controllers\Controller; use App\User;  class UserController extends Controller {         public $gClient;         public function __construct(){             $google_redirect_url = route('glogin');             $this->gClient = new \Google_Client();             $this->gClient->setApplicationName(config('services.google.app_name'));             $this->gClient->setClientId(config('services.google.client_id'));             $this->gClient->setClientSecret(config('services.google.client_secret'));              $this->gClient->setRedirectUri($google_redirect_url);             $this->gClient->setDeveloperKey(config('services.google.api_key'));             $this->gClient->setScopes(array(                                'https://world wide web.googleapis.com/auth/drive.file',                 'https://www.googleapis.com/auth/drive'             ));             $this->gClient->setAccessType("offline");             $this->gClient->setApprovalPrompt("forcefulness");         }         public function googleLogin(Request $request)  {                          $google_oauthV2 = new \Google_Service_Oauth2($this->gClient);             if ($request->get('code')){                 $this->gClient->authenticate($request->get('code'));                 $asking->session()->put('token', $this->gClient->getAccessToken());             }             if ($request->session()->go('token'))             {                 $this->gClient->setAccessToken($request->session()->become('token'));             }             if ($this->gClient->getAccessToken())             {                 //For logged in user, get details from google using acces                 $user=User::find(1);                 $user->access_token=json_encode($asking->session()->get('token'));                 $user->save();                                dd("Successfully authenticated");              } else             {                 //For Guest user, go google login url                 $authUrl = $this->gClient->createAuthUrl();                 render redirect()->to($authUrl);             }         }          public part uploadFileUsingAccessToken(){             $service = new \Google_Service_Drive($this->gClient);             $user=User::detect(1);             $this->gClient->setAccessToken(json_decode($user->access_token,true));             if ($this->gClient->isAccessTokenExpired()) {                                 // save refresh token to some variable                 $refreshTokenSaved = $this->gClient->getRefreshToken();                 // update access token                 $this->gClient->fetchAccessTokenWithRefreshToken($refreshTokenSaved);                                 // // pass access token to some variable                 $updatedAccessToken = $this->gClient->getAccessToken();                  // // append refresh token                 $updatedAccessToken['refresh_token'] = $refreshTokenSaved;                  //Set the new acces token                 $this->gClient->setAccessToken($updatedAccessToken);                                  $user->access_token=$updatedAccessToken;                 $user->save();                              }                         $fileMetadata = new \Google_Service_Drive_DriveFile(array(                 'name' => 'ExpertPHP',                 'mimeType' => 'awarding/vnd.google-apps.folder'));             $folder = $service->files->create($fileMetadata, assortment(                 'fields' => 'id'));             printf("Binder ID: %s\north", $folder->id);                                          $file = new \Google_Service_Drive_DriveFile(array(                             'name' => 'cdrfile.jpg',                             'parents' => array($folder->id)                         ));             $event = $service->files->create($file, array(               'information' => file_get_contents(public_path('images/myimage.jpg')),               'mimeType' => 'application/octet-stream',               'uploadType' => 'media'             ));              // get url of uploaded file             $url='https://drive.google.com/open?id='.$effect->id;             dd($result);                          }  }

cuellarstruch.blogspot.com

Source: http://www.expertphp.in/article/laravel-php-create-folder-and-upload-file-to-google-drive-with-access-token

0 Response to "How to Upload File to Google Drive in Js"

Publicar un comentario

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel