Minggu, 01 Desember 2013

Day 6– File PDF Online bisa DiLihat Orang Banyak

Sebelumnya telah kita bahas mengupload file ke folder tertentu di google drive dengan php dan google drive API. Sekarang kita lanjutkan agar pdf yang sudah diupload bisa dilihat oleh orang banyak

<?php

session_start();
$url_array = explode('?', 'http://'.$_SERVER ['HTTP_HOST'].$_SERVER['REQUEST_URI']);
$url = $url_array[0];

require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_DriveService.php';

$client = new Google_Client();
$client->setClientId('your client id');
$client->setClientSecret('your client secret');
$client->setRedirectUri($url);
$client->setScopes(array('https://www.googleapis.com/auth/drive'));

if (isset($_GET['code'])) {
    $_SESSION['accessToken'] = $client->authenticate($_GET['code']);
    header('location:'.$url);exit;
} elseif (!isset($_SESSION['accessToken'])) {
    $client->authenticate();
}


if (!empty($_POST)) {

    $fileName = $_FILES['dokumen']['name'];    

    if (move_uploaded_file($_FILES['dokumen']['tmp_name'], $fileName)) {
    echo "File is valid, and was successfully uploaded.\n";
} else {
    echo "Possible file upload attack!\n";
}

   $client->setAccessToken($_SESSION['accessToken']);
   $service = new Google_DriveService($client);
   $finfo = finfo_open(FILEINFO_MIME_TYPE);
   $file_path = str_replace('/','\\',dirname($_SERVER['SCRIPT_FILENAME'])).'/'.$fileName;
   $parentId="0Bx3dFOUzrPOidEMwY2Y1d1hGRVE";
   $mime_type = finfo_file($finfo, $file_path);
   
  $file = new Google_DriveFile();
  $file->setTitle($fileName);
  $file->setDescription('This is a '.$mime_type.' document');
  $file->setMimeType($mime_type);

  // Set the parent folder.
  if ($parentId != null) {
    $parent = new Google_ParentReference();
    $parent->setId($parentId);
    $file->setParents(array($parent));
  }

  try {
    $data = file_get_contents($fileName);

    $createdFile = $service->files->insert($file, array(
      'data' => file_get_contents($file_path),
      'mimeType' => $mime_type,
    ));

    //Uncomment the following line to print the File ID
    //print 'File ID: %s' % $createdFile->getId();
    if ($createdFile != null) {
   echo "<a href='https://drive.google.com/file/d/".$createdFile[id]."'>open file</a>";
  }   
    return $createdFile;
   
  } catch (Exception $e) {
    print "An error occurred: " . $e->getMessage();
  }
    finfo_close($finfo);
    //unlink($fileName); 
    header('location:'.$url);exit;
}

include 'index.phtml';
?>

Hasil

image

image

image

Tidak ada komentar:

Posting Komentar