Nishant Bhagat
Nishant Bhagat

Reputation: 103

How To Set Custom File ID While Uploading a File To Google Drive Using Google Drive API? (PHP)

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?

Upvotes: 0

Views: 387

Answers (1)

Alessandro
Alessandro

Reputation: 2998

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

Upvotes: 1

Related Questions