I am using Google Drive API to upload Excel files. I did the API connection correctly. Create a folder and upload the excel file correctly. I can see both of them in my google drive. But, the excel file is empty.. What am I missing here?
my code is below:
$path = "uploads/school_info.xlsx"; //file that I am uploading, inside a folder of my website.
$folder_id = create_folder("School_".$_POST['submit_uid'], "****folder-id****");
$file_name = "School 1";
$success = insert_file_to_drive( $path, $file_name, $folder_id);
// This will insert file into drive and returns boolean values.
function insert_file_to_drive( $file_path, $file_name, $parent_file_id = null ) {
$service = new Google_Service_Drive( $GLOBALS['client'] );
$file = new Google_Service_Drive_DriveFile();
$file->setName( $file_name );
if( !empty( $parent_file_id ) ){
$file->setParents( [ $parent_file_id ] );
}
$result = $service->files->create(
$file,
array(
'data' => file_get_contents($file_path),
//'mimeType' => 'application/octet-stream',
'mimeType' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', //works but still empty excel
)
);
$is_success = false;
if( isset( $result['name'] ) && !empty( $result['name'] ) ){
$is_success = true;
}
return $is_success;
}
ok I found what was the problem. As I wrote in my code above, I had a relative path
$path = "uploads/school_info.xlsx";
when I changed it to full path like this:
$path = "https://www.example.com/uploads/school_info.xlsx";
everything works as expected
thank you all for your time
Answer
I have successfully uploaded a .xlsx file with the following code. Apparently it is very similar to yours, I just change the mimeType and add the uploadType. Once the file is uploaded, from the UI version of Drive, I can access and view the contents of the file. In case it still fails, please repeat the process by downloading a sample file from here.
Code
$service = new Google_Service_Drive($client);
$file = new Google_Service_Drive_DriveFile();
$file->setName('test.xlsx');
$data = file_get_contents('file_example_XLSX_50.xlsx');
$result = $service->files->create($file, array(
'data' => $data,
'mimeType' => 'application/vnd.ms-excel',
'uploadType' => 'multipart'
));
Related
I have used the google drive API to upload files to google drive. The files are being created successfully but they are not opening in google drive, no preview and when I open the file, it says
" could not preview file, You may be offline or with limited connectivity. Try downloading instead.
"
why does this happen?
when I download the file it gives the blank documents.
I am uploading pdf and doc files
how can I solve this issue?
the function that is used to insert the files
function insert_file_to_drive( $file_path, $file_name, $parent_file_id = null ){
$service = new Google_Service_Drive( $GLOBALS['client'] );
$file = new Google_Service_Drive_DriveFile();
$file->setName( $file_name );
if( !empty( $parent_file_id ) ){
$file->setParents( [ $parent_file_id ] );
}
$result = $service->files->create(
$file,
array(
'data' => file_get_contents($file_path),
'mimeType' => 'application/pdf',
'uploadType' => 'media',
)
);
$is_success = false;
if( isset( $result['name'] ) && !empty( $result['name'] ) ){
$is_success = true;
}
return $is_success;
}
I have done the coding using this site
PHP google drive API file upload
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 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
];
I have a Zend Form and offer the option to upload multiple files with the form. I use dropzone.js. When I upload a single file, everything works fine, I get the Post data and the file gets renamed and moved into the correct folder, but as soon I upload 2 files, I get an Error Message: Notice: Array to string conversion which points to $upload->addFilters('File\Rename'.....
What am I doing wrong here? I have everything in a foreach loop, should this not solve the issue? I can not find a solution for it. Anyone got a tip for me?
Here my Sourcecode so far:
$upload = new \Zend\File\Transfer\Adapter\Http();
// Limit the amount of files
$upload->addValidator('Count', false, 2);
// Limit the MIME type of all given files to gif and jpeg images
$upload->addValidator('MimeType', false, array('image/gif', 'image/jpeg',));
if (!$upload->isValid()) {
$data = new JsonModel(array(
'success' => "failed",
'message' => "validation failed",
));
return $data;
}else{
$files = $upload->getFileInfo();
$upload->setDestination('./public/uploads/tmp/');
// loop through the file array
foreach ($files as $file => $info) {
$file_ext = #strtolower(#strrchr($originalName,"."));
$file_ext = #substr($file_ext, 1); // remove dot
$newFilename = md5(uniqid(rand(), true)) .time(). '.' . $file_ext;
$upload->addFilter('File\Rename',
array('target' => $upload->getDestination() . DIRECTORY_SEPARATOR . $newFilename,
'overwrite' => true));
if (!$upload->receive()) {
$data = new JsonModel(array(
'success' => "upload failed",
));
}else{
$data = new JsonModel(array(
'success' => "upload ok",
));
}
return $data;
} // end foreach
}
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..