Convert Local Excel.xlsx File to Google spreadsheet Google DRIVE API - php

I am trying to convert a local Excel.xlsx file with all existent design, format and formulas existent in my local Excel file. How can I do that using Google API with PHP?
What I was doing but not working was :
$client = new \Google_Client();
$client->setApplicationName('Name');
$client->setScopes([\Google_Service_Drive::DRIVE]);
$client->setAccessType('offline');
$client->setAuthConfig($_SERVER['DOCUMENT_ROOT'] . '/credentials.json');
$service = new Google_Service_Drive($client);
$fileID = '';
$path = $_SERVER['DOCUMENT_ROOT'] . '/includes/files/';
$fileName = 'MAIN.xlsx';//this is the file I want to convert to Google sheet
$filePathName = $path.$fileName;
$mimeType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
$file->setMimeType($mimeType);
$createdFile = $service->files->copy($file, array(
'data' => $filePathName,
'mimeType' => $mimeType,
'convert' => true,
));
But that is not working. How should I correct?

I believe your goal as follows.
You want to upload a XLSX file from the local PC to Google Document.
When the XLSX file is uploaded, you want to convert it to Google Spreadsheet.
You want to achieve this using googleapis for PHP.
Modification points:
In your script, the method of "Files: copy" is used. This method copies the file on Google Drive. So I think that this cannot be used for achieving your goal. I think that this is the reason of your issue.
From your error message, I thought that you might be using Drive API v3. I guess that this might be also the reason of your issue.
From above points, when your script is modified, it becomes as follows.
Modified script:
$service = new Google_Service_Drive($client); // Please use your $client here.
$path = $_SERVER['DOCUMENT_ROOT'] . '/includes/files/';
$fileName = 'MAIN.xlsx';//this is the file I want to convert to Google sheet
$filePathName = $path.$fileName;
$file = new Google_Service_Drive_DriveFile();
$file->setName('MAIN.xlsx');
$file->setMimeType('application/vnd.google-apps.spreadsheet');
$data = file_get_contents($filePathName);
$createdFile = $service->files->create($file, array(
'data' => $data,
'uploadType' => 'multipart'
));
printf("%s\n", $createdFile->getId());
Note:
In this modified script, it supposes that you have already been able to get and out values for Google Drive using Drive API. Please be careful this.
In this method, the maximum file size is 5 MB. Please be careful this. When you want to upload the large file, please use the resumable upload. Ref
References:
Upload file data
Create files

Related

Rename uploaded user image Google Cloud

I have the images uploading to google cloud, however I am not able to rename them to a random string before the image is uploaded.
I am wondering if anyone has a solution to this please.
Code:
<?php
# Includes the autoloader for libraries installed with composer
require '../vendor/autoload.php';
use Google\Cloud\Storage\StorageClient;
putenv('GOOGLE_APPLICATION_CREDENTIALS=/PATH TO JSON');
$client = new Google_Client();
$client->useApplicationDefaultCredentials();
$client->setSubject($user_to_impersonate);
$storage = new StorageClient([
'projectId' => 'XXXXXXXXXX'
]);
$bucket = $storage->bucket('abcd');
// Upload a file to the bucket.
$bucket->upload(
fopen('./test.jpg', 'r') // I WANT TO RENAME THIS FILE BEING UPLOADED AND YES i UNDERSTAND IT WILL BE A $_FILE TYPE WHEN I FINISH THE CODE.
);
// Download and store an object from the bucket locally.
$object = $bucket->object('test.jpg');
$object->downloadToFile('/cache/test2.jpg');
?>
Ok the answer is really easy, first you need to read the file that you want to upload. second you will want to generate your new filename, for this i used two user properties (these will most likely stay the same or change very rarely). I also used the timestamp of the request. My theory is no two people should have the same personal information (IP address & user agent) [I will add the users UID once i have finished the prototype.
If anyone else would like the code please see below, and please improve it & share the changes you would make (be great to see what we all come up with.
THIS IS FREE TO USE AND NO NEED TO GIVE CREDIT
$new_file_name = md5(time().md5($_SERVER['REMOTE_ADDR']).md5($_SERVER['HTTP_USER_AGENT']));
$path = "./test.jpg";
$ext = pathinfo($path, PATHINFO_EXTENSION);
$current = file_get_contents('./test.jpg');
$rand = $new_file_name.".".$ext;
echo $rand;
file_put_contents("./cache/".$rand, $current);
// Upload a file to the bucket.
$bucket->upload(
fopen('./cache/'.$rand, 'r')
);
The only problem with it is that you are left with the new files in cache folder but you can add a delete function after the file has been uploaded.
Full code on github
OFFICIAL GITHUB REPO

Convert uploaded file to Google Documents format

I'm trying to upload files to Google Drive but with the attribute convert=true to allow a automatic conversion of upload file to Google Docs format...but it does not work:
$drive_service = new Google_Service_Drive($client);
$file = new Google_Service_Drive_DriveFile();
$file->setTitle("Informe-imaxbd-alfa");
$result = $drive_service->files->insert($file, array(
'data' => file_get_contents("notas-gdrive.docx"),
'mimeType' => 'application/octet-stream',
'uploadType' => 'multipart',
'convert' => FALSE,
));
The file is properly uploaded but without any conversion, why?
You are correct, that the proper mime type Google Drive API accepts is application/msword. I also found out as of writing this, Google Drive API does not support Word .docx format conversion for some reason.
So make sure that not only your extension is in .doc format, but actual document content is also older .doc (Word 97 - 2004) format.

How to get the file URL uploaded in google drive SDK using php

I am using Google Drive SDK to upload files by PHP. now I want to get the Link as string so that I can store it in my Database. But I don't have any idea on how to get it.. this is the code in creating the file in google drive using PHP.
$file = new Google_DriveFile();
$file->setTitle( 'new_pdf' );
$file->setMimeType( 'application/pdf' );
$createdFile = $service->files->insert( $file, array(
'data' => $stringContent,
));
You want one of the properties of $createdFile.
The list of properties is at https://developers.google.com/drive/v2/reference/files
You probably want webContentLink, but it depends on how it is you intend to use the URL.

Files uploaded with Google Drive SDK not viewable

I have created a simple PHP script to play around with Google's Drive SDK. The plan is that eventually we will use Google Drive as a form of CDN for some of our web content (our company already has already upgraded to 1TB).
The code works to a degree, in that it successfully authenticates and uploads a file. The problem is, the file is always broken and cannot be viewed either with Drive itself, or by downloading.
The code is relatively simple, and just fetches an image from Wikipedia and attempts an upload:
<?php
require_once 'Google/Client.php';
require_once 'Google/Service/Drive.php';
require_once 'Google/Service/Oauth2.php';
$client = new Google_Client();
//$client->setUseObjects(true);
//$client->setAuthClass('apiOAuth2');
$client->setScopes(array('https://www.googleapis.com/auth/drive.file'));
$client->setClientId('***');
$client->setClientSecret('***');
$client->setRedirectUri('***');
$client->setAccessToken(authenticate($client));
// initialise the Google Drive service
$service = new Google_Service_Drive($client);
$data = file_get_contents('http://upload.wikimedia.org/wikipedia/commons/3/38/JPEG_example_JPG_RIP_010.jpg');
// create and upload a new Google Drive file, including the data
try
{
//Insert a file
$file = new Google_Service_Drive_DriveFile($client);
$file->setTitle(uniqid().'.jpg');
$file->setMimeType('image/jpeg');
$createdFile = $service->files->insert($file, array(
'data' => $data,
'mimeType' => 'image/jpeg',
));
}
catch (Exception $e)
{
print $e->getMessage();
}
print_r($createdFile);
?>
The print_r statement executes and we get information about the file. However, as I mentioned, the file is not viewable, and appears to be corrupt. Can anyone shed any light on what the issue may be?
After doing some more digging around in the docs (the current public docs are seriously out of date), I found that it's necessary to send another parameter as part of the insert() function's body parameter (the second argument in the function call).
Using the following:
$createdFile = $service->files->insert($doc, array(
'data' => $content,
'mimeType' => 'image/jpeg',
'uploadType' => 'media', // this is the new info
));
I was able to get everything working. I'll leave the question here, as I think it will be very useful until such a time that Google actually updates the documentation for the PHP API.
Source info here
Your code seems to be ok.
Have You tried to download this file from Google Drive afterwards and look at it?
Also I know its abit stupid but have You tried to write file on disk right after using file_get_contents(). You know just to establish point where it goes bad for 100%.

Google Drive SDK (PHP Client Library) - Upload file but unreadable on the Google Drive UI

Here is my code to upload a file:
private function addFile(File $file, $folderProject, User $user) {
$fileToUpload = new Google_DriveFile();
$fileToUpload->setTitle($file->getName());
//set mime type
$fileToUpload->setMimeType($file->getMimeType());
//build parent and set id
$parent = new Google_ParentReference();
$parent->setId($folderProject->getId());
//set parent to file
$fileToUpload->setParents(array($parent));
$data = file_get_contents($file->getPath());
$createdFile = $this->service->files->insert($fileToUpload, array(
'data' => $data,
'mimeType' => $file->getMimeType(),
));
}
When I upload for example a docx using this PHP code the file append to be unreadable on the Google Drive website (it shows up the XML structure of the docx) and it is showing up like this in my Google Drive folder:
And when i try to upload a docx directly through Google Drive UI it showing up like this (what i want):
I'm pretty sure that the problem is coming from the fact the Google
Drive UI tries to open the file in a different way because i uploaded
it through my app, but i don't want that :)
(i have the same problem with other kind of files)
I tried to set the parameter 'convert' = true in the array but then i got this error during the upload:
..convert=true&uploadType=multipart&key=AI39si49a86oqv9fhb9yzXp7FCWL-cSqwFiClHZ‌​qS3Y3r9Hw8ujtSNlZEWZyFKBp_id7LUyFaZTJ97pMeb0XqHznycK7JJ9o_Q:
(500) Internal Error
Documentation: https://developers.google.com/drive/v2/reference/files/insert
=> But anyway i don't think to convert is the right solution, i just want to be able to see the content as if i uploaded the file through the Google Drive UI
If i open the docx from my Google Drive Sync folders and I edit and save it, I will be able to see it through the Google Drive UI (showing with the W logo)
I also getting the same problem.
But the difference is that , I am uploading pdf and able to view pdf in google drive UI.
I need to automatically convert it to google doc format by api code after adding new pdf.
If I change $mimeType = 'application/vnd.google-apps.document'; then got below error
https://www.googleapis.com/upload/drive/v2/files?convert=true&uploadType=multipart: (400) Bad Request
if I add optional parameter
$createdFile = $service->files->insert($file, array(
'data' => $data,
'mimeType' => $mimeType,
'convert' => TRUE
));
Then no change , only pdf upload no conversion takes place.
do u have any suggestion , where I need to exactly add for convert parameter ?

Categories