Php手动选择和上传的文件存储到谷歌驱动器中

时间:2016-11-01 10:33:14

标签: php google-drive-api

这是我的PHP代码。这个脚本几乎正常工作已经设置和创建本地文件自动上传我无法选择和浏览文件所以我需要手动浏览并选择本地文件并存储这些文件谷歌驱动器。是否可以使用谷歌驱动器API(使用PHP)打开和浏览上传到谷歌驱动器的本地文件或文件?

     <?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('client ID');
    $client->setClientSecret('Secret code');
    $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(); 
    } 
    $files= array(); $dir = dir('files'); 
    while ($file = $dir->read()) {
        if ($file != '.' && $file != '..') {
            $files[] = $file;
        } 
    } 
    $dir->close(); 
    if (!empty($_POST)) {
        $client->setAccessToken($_SESSION['accessToken']);
        $service = new Google_DriveService($client);
        $finfo = finfo_open(FILEINFO_MIME_TYPE);
        $file = new Google_DriveFile();

        foreach ($files as $file_name) {
            $file_path = 'files/'.$file_name;
            $mime_type = finfo_file($finfo, $file_path);
            $file->setTitle($file_name);
            $file->setDescription('This is a '.$mime_type.' document');
            $file->setMimeType($mime_type);
            $service->files->insert(
                $file,
                array(
                    'data' => file_get_contents($file_path),
                    'mimeType' => $mime_type
                )
            );
        }
        finfo_close($finfo);
        header('location:'.$url);exit; 
    }     include 'index.phtml'; Index.phtml

<!DOCTYPE html> <html lang="es">  <head>
     <meta charset="UTF-8">
     <title>Google Drive Example App</title>  </head>  <body>
     <ul>
     <?php foreach ($files as $file) { ?>
         <li><?php echo $files; ?></li>
     <?php } ?>
     </ul>
     <form method="post" action="<?php echo $url; ?>">

         <input type="submit" value="enviar" name="submit">
     </form>  </body> </html>

Index.phtml

<!DOCTYPE html> <html lang="es">
 <head>
     <meta charset="UTF-8">
     <title>Google Drive Example App</title>
 </head>
 <body>
     <ul>
     <?php foreach ($files as $file) { ?>
         <li><?php echo $files; ?></li>
     <?php } ?>
     </ul>
     <form method="post" action="<?php echo $url; ?>">

         <input type="submit" value="enviar" name="submit">
     </form>
 </body> </html>

1 个答案:

答案 0 :(得分:0)

那是因为PHP is for server-side scripting。它不包括用户界面。

我认为在这种情况下您需要的是一个向您显示上传窗口的UI。使用此窗口,您可以从计算机中选择文件并将其上传到Google云端硬盘。为此,Google云端硬盘Picker API将对您有很大帮助。