[Php] Google 드라이브 API - 파일 업로드 및 내보내기



Answers

나는 일하는 것을 얻었다. 나는 스코프의 정의가있는 뭔가가 있다고 생각합니다. BTW 여기 에 매우 도움이되는 몇 가지 예제를 발견했습니다. 작업 코드는 다음과 같습니다.

<?php
date_default_timezone_set('Europe/Sofia');
include_once __DIR__ . '/../vendor/autoload.php';
include_once "templates/base.php";
echo pageHeader("File Upload - Uploading a simple file");
/*************************************************
 * Ensure you've downloaded your oauth credentials
 ************************************************/
if (!$oauth_credentials = getOAuthCredentialsFile()) {
  echo missingOAuth2CredentialsWarning();
  return;
}
/************************************************
 * The redirect URI is to the current page, e.g:
 * http://localhost:8080/simple-file-upload.php
 ************************************************/
$redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
$client = new Google_Client();
$client->setAuthConfig($oauth_credentials);
$client->setRedirectUri($redirect_uri);
$client->addScope("https://www.googleapis.com/auth/drive");
$service = new Google_Service_Drive($client);
// add "?logout" to the URL to remove a token from the session
if (isset($_REQUEST['logout'])) {
  unset($_SESSION['upload_token']);
}
/************************************************
 * If we have a code back from the OAuth 2.0 flow,
 * we need to exchange that with the
 * Google_Client::fetchAccessTokenWithAuthCode()
 * function. We store the resultant access token
 * bundle in the session, and redirect to ourself.
 ************************************************/
if (isset($_GET['code'])) {
  $token = $client->fetchAccessTokenWithAuthCode($_GET['code']);
  $client->setAccessToken($token);
  // store in the session also
  $_SESSION['upload_token'] = $token;
  // redirect back to the example
  header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
// set the access token as part of the client
if (!empty($_SESSION['upload_token'])) {
  $client->setAccessToken($_SESSION['upload_token']);
  if ($client->isAccessTokenExpired()) {
    unset($_SESSION['upload_token']);
  }
} else {
  $authUrl = $client->createAuthUrl();
}
/************************************************
 * If we're signed in then lets try to upload our
 * file. For larger files, see fileupload.php.
 ************************************************/
if ($_SERVER['REQUEST_METHOD'] == 'POST' && $client->getAccessToken()) {

// CREATE A NEW FILE
  $file = new Google_Service_Drive_DriveFile(array(
    'name' => 'sample',
    'mimeType' => 'application/vnd.google-apps.presentation'
  ));
  $pptx = file_get_contents("sample.docx"); // read power point pptx file
  //declare opts params
  $optParams = array(
    'uploadType' => 'multipart',
    'data' => $pptx,
    'mimeType' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
  );
  //import pptx file as a Google Slide presentation
  $createdFile = $service->files->create($file, $optParams);
  //print google slides id
  //print "File id: ".$createdFile->id;

  $optParams2 = array(
    'fileId' => $createdFile->id,
    'mimeType' => 'application/pdf'
  );


  $response = $service->files->export($createdFile->id, 'application/pdf', array(
  'alt' => 'media' ));
//print_r($response);
  $content = $response->getBody()->getContents();
///rint_r($content);

$data = $content;
file_put_contents('test_ppt.pdf',$data);

}
?>

<div class="box">
<?php if (isset($authUrl)): ?>
  <div class="request">
    <a class='login' href='<?= $authUrl ?>'>Connect Me!</a>
  </div>
<?php elseif($_SERVER['REQUEST_METHOD'] == 'POST'): ?>
  <div class="shortened">
    <p>Your call was successful! Check your drive for the following files:</p>
    <ul>


    </ul>
  </div>
<?php else: ?>
  <form method="POST">
    <input type="submit" value="Click here to upload two small (1MB) test files" />
  </form>
<?php endif ?>
</div>

<?= pageFooter(__FILE__) ?>

다른 형식으로 변환하려면 참조 및 여기에 있는 Mime 유형을 변경하십시오. 여기여기

Question

Google 드라이브를 통해 파일을 업로드 한 다음 다른 형식으로 내 보내야합니다. 예를 들어 DOCX를 업로드하고 PDF로 내 보냅니다. 나는 REST 빠른 시작과 업로드 파일 가이드를 따라 왔습니다. 코드를 실행 한 후에 오류가 발생합니다.

치명적 오류 : 잡히지 않은 예외 'Google_Service_Exception, "message": "불충분 한 권한"

권한 문제가 있지만 수정 방법을 모르겠습니다. 다음은 내가 사용하는 코드입니다.

date_default_timezone_set('Europe/Sofia');

require_once __DIR__ . '/vendor/autoload.php';

define('APPLICATION_NAME', 'Drive API PHP Quickstart');
define('CREDENTIALS_PATH', '~/.credentials/drive-php-quickstart.json');
define('CLIENT_SECRET_PATH', __DIR__ . '/client_secret.json');
// If modifying these scopes, delete your previously saved credentials
// at ~/.credentials/drive-php-quickstart.json
define('SCOPES', implode(' ', array(
  Google_Service_Drive::DRIVE_METADATA_READONLY)
));
//i've tried to change the scope to ::DRIVE, but still get the same error

if (php_sapi_name() != 'cli') {
  throw new Exception('This application must be run on the command line.');
}

/**
 * Returns an authorized API client.
 * @return Google_Client the authorized client object
 */
function getClient() {
  $client = new Google_Client();
  $client->setApplicationName(APPLICATION_NAME);
  $client->setScopes(SCOPES);
  $client->setAuthConfig(CLIENT_SECRET_PATH);
  $client->setAccessType('offline');

  // Load previously authorized credentials from a file.
  $credentialsPath = expandHomeDirectory(CREDENTIALS_PATH);
  if (file_exists($credentialsPath)) {
    $accessToken = json_decode(file_get_contents($credentialsPath), true);
  } else {
    // Request authorization from the user.
    $authUrl = $client->createAuthUrl();
    printf("Open the following link in your browser:\n%s\n", $authUrl);
    print 'Enter verification code: ';
    $authCode = trim(fgets(STDIN));

    // Exchange authorization code for an access token.
    $accessToken = $client->fetchAccessTokenWithAuthCode($authCode);

    // Store the credentials to disk.
    if(!file_exists(dirname($credentialsPath))) {
      mkdir(dirname($credentialsPath), 0700, true);
    }
    file_put_contents($credentialsPath, json_encode($accessToken));
    printf("Credentials saved to %s\n", $credentialsPath);
  }
  $client->setAccessToken($accessToken);

  // Refresh the token if it's expired.
  if ($client->isAccessTokenExpired()) {
    $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
    file_put_contents($credentialsPath, json_encode($client->getAccessToken()));
  }
  return $client;
}

/**
 * Expands the home directory alias '~' to the full path.
 * @param string $path the path to expand.
 * @return string the expanded path.
 */
function expandHomeDirectory($path) {
  $homeDirectory = getenv('HOME');
  if (empty($homeDirectory)) {
    $homeDirectory = getenv('HOMEDRIVE') . getenv('HOMEPATH');
  }
  return str_replace('~', realpath($homeDirectory), $path);
}

// Get the API client and construct the service object.
$client = getClient();
$service = new Google_Service_Drive($client);

// Print the names and IDs for up to 10 files.
$optParams = array(
  'pageSize' => 10,
  'fields' => 'nextPageToken, files(id, name)'
);
$results = $service->files->listFiles($optParams);

if (count($results->getFiles()) == 0) {
  print "No files found.\n";
} else {
  print "Files:\n";
  foreach ($results->getFiles() as $file) {
    printf("%s  FILE_ID(%s)\n", $file->getName(), $file->getId());
  }
}


//The error I get is in this block:

$fileMetadata = new Google_Service_Drive_DriveFile(array(
  'name' => 'photo.jpg'));
$content = file_get_contents('photo.jpg');
$file = $service->files->create($fileMetadata, array(
  'data' => $content,
  'mimeType' => 'image/jpeg',
  'uploadType' => 'multipart',
  'fields' => 'id'));
printf("File ID: %s\n", $file->id);

편집 : 마지막 블록까지 코드가 작동하는지, 파일을 성공적으로 나열하는지, 그리고 마지막 10 개 행이 오류를 던졌습니다.




Links