我想使用PHP将上传的文件保存在Google云端硬盘中。我没有得到任何回复。如果任何人可以建议将不胜感激。以下是我的代码 我从这个github下载API表格我无法获得输出请帮助我
<?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('<client secret>');
$client->setRedirectUri($url);
$client->setScopes(array('https://www.googleapis.com/auth/drive'));
if (isset($_GET['code'])) {
echo $_SESSION['accessToken'] ;
$_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';
答案 0 :(得分:0)
您正尝试使用google的多部分(请参阅this)上传方法。
// Getting Files
$files= array();
$dir = dir('files');
while ($file = $dir->read()) {
if ($file != '.' && $file != '..') {
$files[] = $file;
}
}
$dir->close();
if (!empty($_POST)) {
// set access token
$client->setAccessToken($_SESSION['accessToken']);
// service object
$service = new Google_DriveService($client);
// drive file object
$file = new Google_DriveFile();
foreach ($files as $file_name) {
$file_path = 'files/'.$file_name;
$file->setTitle($file_name);
// Use create instead of insert
// store response on $result array
$result[] = $service->files->create(
$file,
array(
'data' => file_get_contents($file_path),
'mimeType' => 'application/octet-stream',
'uploadType' => 'multipart'
)
);
}
// check response
print_r($result);
}
您必须为所有类型的文件设置'mimeType' => 'application/octet-stream'
。如果您要发送元数据,请使用uploadtype作为multipart!。
我还没有测试过这段代码。如果它对您有用,请告诉我