I use
"google/apiclient": "1.1.7",
"asimlqt/php-google-spreadsheet-client": "2.3.7",
"phpoffice/phpexcel": "1.8.1"
And I create new spread sheet in google drive
"google/apiclient":
$service = new \Google_Service_Drive($client->getGoogleClient());
$file = new \Google_Service_Drive_DriveFile();
$file->setMimeType('application/vnd.google-apps.spreadsheet');
$insertArray = [
'mimeType' => 'application/vnd.google-apps.spreadsheet',
];
try {
$createdFile = $service->files->insert($file, $insertArray);
$spreadsheetId = $createdFile->getId();
} catch (\Exception $e) {
$e->getMessage()
}
and I have alternativeUrl - https://docs.google.com/spreadsheets/d/xxxxx/edit?usp=drivesdk and this is ok, go to this url I have emty google spread sheet
And I know how to upload exist xls file, generate in PHPExel and save and upload in google drive
"phpoffice/phpexcel":
$phpExcel = new \PHPExcel();
$ews = $phpExcel->getSheet(0);
$ews->setTitle(Reports::LIST_AOG);
$objWriter = new \PHPExcel_Writer_Excel2007($phpExcel);
$path = 'uploads/';
$rootDir = $this->get('kernel')->getRootDir() . '/../web/';
$filePath = $rootDir . $path.$nameFile;
$objWriter->save($filePath);
$fileUpload = new File($filePath);
$insertArray = [
'mimeType' => $fileUpload->getMimeType(),
'uploadType' => 'media',
'data' => file_get_contents($fileUpload)
];
"google/apiclient":
$service = new \Google_Service_Drive($client->getGoogleClient());
$file = new \Google_Service_Drive_DriveFile();
$file->setTitle($nameFile);
$file->setMimeType($fileUpload->getMimeType());
try {
$createdFile = $service->files->insert($file, $insertArray);
$spreadsheetId = $createdFile->getId();
} catch (\Exception $e) {
$e->getMessage()
}
and I have alternativeUrl - https://drive.google.com/file/d/xxxxxx/view?usp=drivesdk and this is ok, go to this url I see file and button open in GoogleSpreadSheet
and this moment my xls file not googleSpreadSheet, only when I open my file in googleSpreadSheet this file will get googleSpreadSheetId
and I can get google spread sheet by id or title
"asimlqt/php-google-spreadsheet-client":
$serviceRequest = new DefaultServiceRequest($arrayAccessTokenClient['access_token']);
ServiceRequestFactory::setInstance($serviceRequest);
$spreadsheetService = new SpreadsheetService();
$scopeSpreadSheet = $spreadsheetService->getSpreadsheets();
$spreadsheetByTitle = $scope->getByTitle($createdFile->getTitle());
$spreadsheetById = $spreadsheetService->getSpreadsheetById($spreadsheetId);
I try replace momeType file in application/vnd.google-apps.spreadsheet but have in googledrive emty googleSpreadSheet
And I refuse to believe that I can not download my file in googleSpreadSheet immediately or right one request. I try find solution but the two day search yielded no results.
How to download my xls file in googleSpreadSheed in one moment ??? Help please
I find :)
convert boolean Whether to convert this file to the corresponding Google Docs format. (Default: false)
$insertArray = [
'mimeType' => $fileUpload->getMimeType(),
'uploadType' => 'media',
'data' => file_get_contents($fileUpload),
'convert' => true
];
Related
On my site I use google api to upload images in folder. Actually, there is no official documentation from google how to use api using php, only python, js and etc. Current problem is that I get no errors, but file isn't uploading. I'm 100% sure that my service workers work (sorry for such bad english) properly. Below I put my php code for uploading images:
<?php
include '../vendor/autoload.php';
function handleGoogleDrive($file)
{
//connecting to google drive
$client = new \Google_Client();
$client->setApplicationName('Somesite');
$client->setScopes([\Google_Service_Drive::DRIVE]);
$client->setAccessType('offline');
$client->setAuthConfig('./credentials.json');
$client->setClientId('2445617429-6k99ikago0s0jdh5q5k3o37de6lqtsd3.apps.googleusercontent.com');
$client->setClientSecret('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');
$service = new Google_Service_Drive($client);
//counting amount of files in folder, there is no real reason in doing that
//it is just a test of connecting
$folder_id = '1eQtNOJjlA2CalZYb90bEs34IaP6v9ZHM';
$options = [
'q' => "'" . $folder_id . "' in parents",
'fields' => 'files(id, name)'
];
//printing result
$results = $service->files->listFiles($options);
echo count($results->getFiles());
//trying to add file
$data = file_get_contents("../test.jpg");
$file = new Google_Service_Drive_DriveFile();
$file->setName(uniqid(). '.jpg');
$file->setDescription('A test document');
$file->setMimeType('image/jpeg');
$new_file = $service->files->create($file, [
'data' => $data,
'mimeType' => 'image/jpeg',
'uploadType' => 'multipart',
]);
print_r($new_file);
}
This is my standard upload code for uploading.
Try removing 'uploadType' => 'multipart', in your code.
I also cant see you setting the folder id when you upload your file which means its going to root directory.
// Upload a file to the users Google Drive account
try{
$filePath = "image.png";
$folder_id = '1eQtNOJjlA2CalZYb90bEs34IaP6v9ZHM';
$fileMetadata = new Drive\DriveFile();
$fileMetadata->setName("image.png");
$fileMetadata->setMimeType('image/png');
$fileMetadata->setParents(array($folder_id));
$content = file_get_contents($filePath);
$mimeType=mime_content_type($filePath);
$request = $service->files->create($fileMetadata, array(
'data' => $content,
'mimeType' => $mimeType,
'fields' => 'id'));
printf("File ID: %s\n", $request->id);
}
catch(Exception $e) {
// TODO(developer) - handle error appropriately
echo 'Message: ' .$e->getMessage();
}
Remember if you are using a service account, files are uploaded to the service accounts drive account unless you add the folder you want to upload the file to.
files list
// Print the next 10 events on the user's drive account.
try{
$optParams = array(
'pageSize' => 10,
'fields' => 'files(id,name,mimeType)'
);
$results = $service->files->listFiles($optParams);
$files = $results->getFiles();
if (empty($files)) {
print "No files found.\n";
} else {
print "Files:\n";
foreach ($files as $file) {
$id = $file->id;
printf("%s - (%s) - (%s)\n", $file->getId(), $file->getName(), $file->getMimeType());
}
}
}
catch(Exception $e) {
// TODO(developer) - handle error appropriately
echo 'Message: ' .$e->getMessage();
}
Using the code which was suggested to me, this is full solution.
(Thanks everybody who helped me)
<?php
include '../vendor/autoload.php';
function handleGoogleDrive($file)
{
//connecting to google drive
$client = new \Google_Client();
$client->setClientId('YOUR ID IN SECRET FILE');
$client->setClientSecret(YOUR SECRET IN JSON FILE);
$client->setRedirectUri(YOUR REDIRECT URI);
//you should register redirect uri
$client->setApplicationName('Somesite');
$client->setScopes([\Google_Service_Drive::DRIVE]);
$client->setAuthConfig('./credentials.json');
$service = new Google_Service_Drive($client);
try{
$filePath = "../test.jpg";
$folder_id = 'YOUR FOLDER ID';
$fileMetadata = new Google_Service_Drive_DriveFile();
$fileMetadata->setName("image.png");
$fileMetadata->setMimeType('image/png');
$fileMetadata->setParents(array($folder_id));
$content = file_get_contents($filePath);
$mimeType=mime_content_type($filePath);
$request = $service->files->create($fileMetadata, array(
'data' => $content,
'mimeType' => $mimeType,
'fields' => 'id'));
printf("File ID: %s\n", $request->id);
}
catch(Exception $e) {
echo 'Message: ' .$e->getMessage();
}
catch(Exception $e) {
echo 'Message: ' .$e->getMessage();
}
try{
$optParams = array(
'pageSize' => 10,
'fields' => 'files(id,name,mimeType)'
);
$results = $service->files->listFiles($optParams);
$files = $results->getFiles();
if (empty($files)) {
print "No files found.\n";
} else {
print "Files:\n";
foreach ($files as $file) {
$id = $file->id;
printf("%s - (%s) - (%s)\n", $file->getId(), $file->getName(), $file->getMimeType());
}
}
}
catch(Exception $e) {
// TODO(developer) - handle error appropriately
echo 'Message: ' .$e->getMessage();
}
}
I am trying to allow file uploads to overwrite the previous copy and keep the revision history permanent within Google Drive. Also...Do I need to upload with a set ID or is the file name going to overwrite natively?
Here is a sample of what I have as a test function:
function uploadFile($filename = "")
{
$title="testFile";
$description="Testing the upload of the file";
$mimeType="image/jpeg";
$filename = ROOTPATH."IMG_1232.JPG"; //Temporarily overriding $filename for testing.
$file = new Google_Service_Drive_DriveFile();
$file->setName($title);
$file->setDescription($description);
$file->setMimeType($mimeType);
// Set the parent folder.
if ($parentId != null) {
$parent = new Google_Service_Drive_ParentReference();
$parent->setId($parentId);
$file->setParents(array($parent));
}
try {
$data = file_get_contents($filename);
$this->startGDService();
$createdFile = $this->service->files->create($file, array(
'data' => $data,
'mimeType' => $mimeType,
'keepRevisionForever' => true // <---This doesn't seem to work.
));
return $createdFile;
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
}
return;
}
Looks like I was using the wrong function. The create function will always create a file on the drive. To overwrite a particular file, you need to use the update() function. See here:
function updateFile($filename, $fileID)
{
$this->startGDService();
$filename = UPLOAD_PATH.$filename;
$mimetype = mime_content_type ($filename);
try {
$emptyFile = new Google_Service_Drive_DriveFile();
$data = file_get_contents($filename);
$this->service->files->update($fileID, $emptyFile, array(
'data' => $data,
'mimeType' => $mimetype,
'uploadType' => 'multipart',
'keepRevisionForever' => true
));
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
}
}
I am working on a project in which I need to upload a .xlsx file to my google drive via Google Drive API. Then also to get back the link so I can store it into MySQL Database.
The Uploading part is done. The problem is, how can I get back the file link so I can edit it using Google Sheets. I think I need to add Custom File ID To my file. I really don't know where to add it. My code is below:
// Get the API client and construct the service object.
$client = getClient();
$service = new Google_Service_Drive($client);
$filefullname=$_GET['accid'].' '.$_GET['name'].'.xlsx';
// UPLOADING OF FILE TO GOOGLE DRIVE////////////////////////////////////
//fopen('./client_sheets/'.$_GET['name'], "w");
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$file = new Google_Service_Drive_DriveFile();
$file_path = './client_sheets/'.$filefullname;
$mime_type = finfo_file($finfo, $file_path);
$file->setName($filefullname);
$file->setDescription('This file contains details about: '.$filefullname.' || Client of GT Security');
$file->setMimeType($mime_type);
$file->setName($filefullname);
$createdFile = $service->files->create(
$file,
array(
'data' => file_get_contents($file_path),
'mimeType' => $mime_type,
'fields' => 'id'
)
);
print 'File ID: %s' % $createdFile->getId();
More info: I used PhpSpreadsheet to create the .xlsx file. Please can somebody add the FileID Field for me? Also, can somebody explain to me how to get the file link so I can edit it using Google Sheets?
In this case you can use the Google Drive automatic conversion feature. When you create the file in google drive it will be automatically converted to a spreadsheet file. So that you can open it via the spreadsheet service and get the url you need to store in your db.
Create and convert the .xlsx to a spreadsheet file:
$fileMetadata = new Google_Service_Drive_DriveFile(array(
'name' => $filefullname,
'mimeType' => 'application/vnd.google-apps.spreadsheet'));
$content = file_get_contents($file_path);
$file = $driveService->files->create($fileMetadata, array(
'data' => $content,
'mimeType' => 'text/csv',
'uploadType' => 'multipart',
'fields' => 'id'));
Get the spreadsheet url:
$spreadsheetId = $file->id;
$sheetService = new Google_Service_Sheets($client);
$response = $service->spreadsheets->get($spreadsheetId);
$sheetUrl = $response->getSpreadsheetUrl();
References:
PHP Spreadsheet class methods
Import to Google Docs types
I'm trying to update the content of the file. Use the PHP function:
function updateFile($service, $fileId, $newTitle, $newDescription, $newMimeType, $newFileName, $newRevision) {
try {
// First retrieve the file from the API.
$file = $service->files->get($fileId);
// File's new metadata.
$file->setTitle($newTitle);
$file->setDescription($newDescription);
$file->setMimeType($newMimeType);
// File's new content.
$data = file_get_contents($newFileName);
$additionalParams = array(
'newRevision' => $newRevision,
'data' => $data,
'mimeType' => $newMimeType
);
// Send the request to the API.
$updatedFile = $service->files->update($fileId, $file, $additionalParams);
return $updatedFile;
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
}
}
....
$data = retrieveAllFiles($service);
$fileName = 'test.txt';
$mimeType = mime_content_type('./'.$fileName);
$res = updateFile($service, $data[0]['id'], $data[0]['title'], 'update', $mimeType, $fileName, true);
I'm trying to add a text file line "test string". Function updates the data file (description, lastModifyingUser...), but the content of the file remains the same. Who can tell what's wrong?
In additionalParams need to add :
'uploadType' => 'multipart',
or
'uploadType' => 'media',
Hope it helps!
So I've been having weird issues with PHP upload with GAPI. The file actually gets created on the drive but for some reason the data doesn't make it to Google and it just creates a file with 0 bytes.
Here's my code:
function uploadFile($service, $title, $description, $parentId, $mimeType, $filepath) {
$mimeType = "image/png";
$title = "test.png";
$file = new Google_Service_Drive_DriveFile();
$file->setTitle($title);
$file->setDescription($description);
$file->setMimeType($mimeType);
// Set the parent folder.
if ($parentId != null) {
$parent = new Google_Service_Drive_ParentReference();
$parent->setId($parentId);
$file->setParents(array($parent));
}
try {
$data = file_get_contents();
$createdFile = $service->files->insert($file, array(
'data' => $data,
'mimeType' => $mimeType,
));
// Uncomment the following line to print the File ID
// print 'File ID: %s' % $createdFile->getId();
//return $createdFile;
} catch (Exception $e) {
echo "An error occurred: " . $e->getMessage();
}
}
Everything is authenticated so I know that's not the problem. When I output $data, I get the mess of crap that you usually get when pulling a file so I know that's not the issue.. All of the scopes should be right but here they are anyways:
$client->addScope("https://www.googleapis.com/auth/drive");
$client->addScope("https://www.googleapis.com/auth/drive.file");
$client->addScope("https://www.googleapis.com/auth/drive.appdata");
$client->addScope("https://www.googleapis.com/auth/drive.scripts");
$client->addScope("https://www.googleapis.com/auth/drive.apps.readonly");
$client->addScope("https://www.googleapis.com/auth/drive.metadata.readonly");
$client->addScope("https://www.googleapis.com/auth/drive.readonly");
No documentation I can find on this problem so any help would be really appreciated!
I was able to figure this out and wanted to leave this for anyone else that might have this issue.
Ended up looking through the source code and noticed an If statement that was not getting fired.
Change
$createdFile = $service->files->insert($file, array(
'data' => $data,
'mimeType' => $mimeType,
));
To
$createdFile = $service->files->insert($file, array(
'data' => $data,
'mimeType' => $mimeType,
'uploadType' => 'media' //add this for pdfs to work
));
It's just that easy! Hate it when it's that easy..