繁体   English   中英

如何在使用 Google Drive API 将文件上传到 Google Drive 时设置自定义文件 ID? (PHP)

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

我正在开发一个项目,在该项目中我需要通过 Google Drive API 将 .xlsx 文件上传到我的 Google Drive。 然后还要取回链接,以便我可以将其存储到 MySQL 数据库中。

上传部分完成。 问题是,我怎样才能取回文件链接,以便我可以使用 Google 表格对其进行编辑。 我想我需要在我的文件中添加自定义文件 ID。 我真的不知道在哪里添加它。 我的代码如下:

// 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();

更多信息:我使用 PhpSpreadsheet 创建 .xlsx 文件。 请问有人可以为我添加 FileID 字段吗? 另外,有人可以向我解释如何获取文件链接,以便我可以使用 Google 表格对其进行编辑吗?

在这种情况下,您可以使用 Google Drive 自动转换功能。 当您在 google drive 中创建文件时,它会自动转换为电子表格文件。 这样您就可以通过电子表格服务打开它并获取需要存储在数据库中的 url。

创建 .xlsx 并将其转换为电子表格文件:

$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'));

获取电子表格网址:

$spreadsheetId = $file->id;

$sheetService = new Google_Service_Sheets($client);
$response = $service->spreadsheets->get($spreadsheetId);
$sheetUrl = $response->getSpreadsheetUrl();

参考:

PHP 电子表格类方法

导入到 Google 文档类型

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM