PHP将PDF上传到Google Drive API

时间:2018-06-01 13:10:53

标签: php azure curl google-api google-api-php-client

我在PHP中创建了网站。基本上它是一个发送文件类的项目。它使用Azure中的文档存储我将调用并将其发送到Azure。现在我想发送电子邮件以及存储在Google云端硬盘中。

因此应将其存储为具有公共访问权限的驱动器。我创建了以下代码。它工作正常我不想要用户的任何输入。

  $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);

我想使用cURL或使用API​​从Azure URL上传。邮件发送时,它会同时自动上传到驱动器。

问题更新

我有发送邮件的功能,这是完美的工作。我想将一个附件存储到谷歌驱动器并检索该路径到数据库的路径存储。

这一切都将基于API,无需用户交互。该文件是格式的PDF,而不是特定的字节,根据文件的数据不同。

问题:

当我将文件上传到云端硬盘原始文件名时,重命名为无标题。这是代码。

function uploadFile($credentials, $filename, $targetPath)
{

    global $GAPIS;
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $GAPIS . 'upload/drive/v2/files?uploadType=media');

    curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
    //curl_setopt($ch, CURLOPT_POSTFIELDS, array("title" =>"newfile.txt"));
    curl_setopt($ch, CURLOPT_POSTFIELDS, file_get_contents($filename));

    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER,
            array('Content-Type : text/plain', 'Content-Length:' . filesize($filename),
                    'Authorization: Bearer ' . getAccessToken($credentials))
    );

    $postResult = curl_exec($ch);
    curl_close($ch);

    return json_decode($postResult, true);
}

==========================================

更新了代码(添加了代码的问题,但仍然在驱动器中遇到Untitle.pdf问题)

==========================================

<?php

$GAPIS = 'https://www.googleapis.com/';
$GAPIS_AUTH = $GAPIS . 'auth/';
$GOAUTH = 'https://accounts.google.com/o/oauth2/';

$CLIENT_ID = '709846732498-xxxxxxxx';
$CLIENT_SECRET = 'XXXXXXXXXXXXXX';
$REDIRECT_URI = 'http' . ($_SERVER['SERVER_PORT'] == 80 ? '' : 's') . '://' . $_SERVER['SERVER_NAME'] . $_SERVER['SCRIPT_NAME'];
$SCOPES = array($GAPIS_AUTH . 'drive', $GAPIS_AUTH . 'drive.file', $GAPIS_AUTH . 'userinfo.email', $GAPIS_AUTH . 'userinfo.profile');
$STORE_PATH = 'credentials.json';

function uploadFile($credentials, $filename, $targetPath)
{

    global $GAPIS;
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $GAPIS . 'upload/drive/v2/files?uploadType=media');

    curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, file_get_contents($filename));
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER,
            array('Content-Type : application/pdf', 'Content-Length:' . filesize($filename),
                    'Authorization: Bearer ' . getAccessToken($credentials))
    );

    $postResult = curl_exec($ch);
    curl_close($ch);

    return json_decode($postResult, true);
}

function getStoredCredentials($path)
{

    $credentials = json_decode(file_get_contents($path), true);

    if (isset($credentials['refresh_token']))
        return $credentials;

    $expire_date = new DateTime();
    $expire_date->setTimestamp($credentials['created']);
    $expire_date->add(new DateInterval('PT' . $credentials['expires_in'] . 'S'));

    $current_time = new DateTime();

    if ($current_time->getTimestamp() >= $expire_date->getTimestamp())
    {
        $credentials = null;
        unlink($path);
    }

    return $credentials;
}

function storeCredentials($path, $credentials)
{

    $credentials['created'] = (new DateTime())->getTimestamp();
    file_put_contents($path, json_encode($credentials));
    return $credentials;
}

function requestAuthCode()
{

    global $GOAUTH, $CLIENT_ID, $REDIRECT_URI, $SCOPES;
    $url = sprintf($GOAUTH . 'auth?scope=%s&redirect_uri=%s&response_type=code&client_id=%s&approval_prompt=force&access_type=offline',
            urlencode(implode(' ', $SCOPES)), urlencode($REDIRECT_URI), urlencode($CLIENT_ID)
    );
    header('Location:' . $url);
}

function requestAccessToken($access_code)
{

    global $GOAUTH, $CLIENT_ID, $CLIENT_SECRET, $REDIRECT_URI;
    $url = $GOAUTH . 'token';
    $post_fields = 'code=' . $access_code . '&client_id=' . urlencode($CLIENT_ID) . '&client_secret=' . urlencode($CLIENT_SECRET)
            . '&redirect_uri=' . urlencode($REDIRECT_URI) . '&grant_type=authorization_code';

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields);
    curl_setopt($ch, CURLOPT_POST, true);

    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_URL, $url);

    $result = curl_exec($ch);

    curl_close($ch);

    return json_decode($result, true);
}

function getAccessToken($credentials)
{

    $expire_date = new DateTime();
    $expire_date->setTimestamp($credentials['created']);
    $expire_date->add(new DateInterval('PT' . $credentials['expires_in'] . 'S'));

    $current_time = new DateTime();

    if ($current_time->getTimestamp() >= $expire_date->getTimestamp())
        return $credentials['refresh_token'];
    else
        return $credentials['access_token'];

}

function authenticate()
{

    global $STORE_PATH;

    if (file_exists($STORE_PATH))
        $credentials = getStoredCredentials($STORE_PATH);
    else
        $credentials = null;

    if (!(isset($_GET['code']) || isset($credentials)))
        requestAuthCode();

    if (!isset($credentials))
        $credentials = requestAccessToken($_GET['code']);

    if (isset($credentials) && isset($credentials['access_token']) && !file_exists($STORE_PATH))
        $credentials = storeCredentials($STORE_PATH, $credentials);

    return $credentials;
}

$credentials = authenticate();

$result = uploadFile($credentials, 'example.pdf', '');

if (!isset($result['id']))
    throw new Exception(print_r($result));
else
    echo 'File copied successfuly (file Id: ' . $result['id'] . ')';

echo '<pre>'; print_r($result);

3 个答案:

答案 0 :(得分:2)

我仍然不完全确定我理解你的问题。假设您只想在php或curl上传文件,这里有两个选项。

上传到Google云端硬盘分为两部分,第一部分是您创建的元数据,即文件名和有关罚款的基本信息。第二部分是您上传文件实际数据的位置。

$fileMetadata = new Google_Service_Drive_DriveFile(array(
    'name' => 'My Report',
    'mimeType' => 'application/vnd.google-apps.spreadsheet'));
$content = file_get_contents('files/report.csv');
$file = $driveService->files->create($fileMetadata, array(
    'data' => $content,
    'mimeType' => 'text/csv',
    'uploadType' => 'multipart',
    'fields' => 'id'));
printf("File ID: %s\n", $file->id);

代码摘自media upload

如果你想在卷曲中插入元数据不应该是一个问题,你的问题将是上传文件本身。您需要POST元数据以创建空文件并捕获其文件ID。然后使用file-id进行内容上传。您可以在此处找到有关您需要点击的请求的更多信息simple upload request

代码可能看起来像这样但是你必须再次传递文件ID。

curl 
--silent 
--request POST 
--data-binary "@c:\temp\myfile.jpg"         
-OL MyFolder\myfile2.jpeg
-H "Slug: myfile3.jpg" 
-H "Authorization: Bearer [your access token here]" 
-H "Content-Type: image/jpeg {"fileid":"1234"}" 
"https://www.googleapis.com/upload/drive/v3/files?uploadType=media" 

注意我还没有测试curl的上传,这只是猜测。

答案 1 :(得分:2)

经过https://developers.google.com/drive/api/v3/simple-upload,这应该有效:

exceed 100kg OR exceeds 60min

答案 2 :(得分:1)

您可以使用Logic Apps将文件从Azure Blob存储发送到Google云端硬盘以及电子邮件附件。

https://docs.microsoft.com/en-us/azure/connectors/connectors-create-api-azureblobstorage

或者,Azure Blob中存储的文件可以是带有公共URL的地址,假设您在容器和/或blob上设置了正确的权限。