我已经完成了谷歌api集成代码以及文件上传到驱动器。我有关于上传文件名的问题是“Untitled”。请查看代码并指导我缺少的内容。
<?php
$GAPIS = 'https://www.googleapis.com/';
$GAPIS_AUTH = $GAPIS . 'auth/';
$GOAUTH = 'https://accounts.google.com/o/oauth2/';
$CLIENT_ID = '709846732498-t19mhuuvq0nqtng5ogg8XXXXXX0im8.apps.googleusercontent.com';
$CLIENT_SECRET = 'XXXXXXXXKa';
$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');
//$content = { title "mypdf.pdf", description = "mypdf.pdf", mimeType = "application/pdf" };
$contentArry = array('title' =>'veridoc' );
$contentArry = json_encode($contentArry);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
//curl_setopt($ch, CURLOPT_POSTFIELDS,$contentArry);
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, 'veridoc.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);
`
答案 0 :(得分:2)
通过https://developers.google.com/drive/api/v3/reference/files/update上的文档,重命名文件,使用新名称向https://www.googleapis.com/drive/v3/files/<fileId>
发送PATCH请求,在您的情况下,我想这将是
$postResult = curl_exec ( $ch );
$parsed = json_decode ( $postResult, true );
if (! $parsed || $parsed ['code'] !== 200) {
throw new \RuntimeException ( 'google api error: ' . $postResult );
}
$id = $parsed ['id']; // ?? wait, is it id or fileId?
curl_setopt_array ( $ch, array (
CURLOPT_URL => 'https://www.googleapis.com/drive/v3/files/' . urlencode ( $id ),
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => json_encode ( array (
'name' => basename ( $filename )
) ),
CURLOPT_CUSTOMREQUEST => 'PATCH',
CURLOPT_HTTPHEADER => array (
'Content-Type : application/json',
'Authorization: Bearer ' . getAccessToken ( $credentials )
)
) );
curl_exec($ch);
ps,使用CURLOPT_POSTFIELDS时不要手动设置Content-Length
标题,因为curl会为你做,如果你使用multipart / form-data,你自己设置的长度很可能是甚至是错误的(不关心你的代码,因为你没有使用multipart / form-data,但这是一个学习的好习惯,但要摆脱它。)