【问题标题】:How To Set Custom File ID While Uploading a File To Google Drive Using Google Drive API? (PHP)使用 Google Drive API 将文件上传到 Google Drive 时如何设置自定义文件 ID? (PHP)
【发布时间】:2020-03-21 10:44:10
【问题描述】:

我正在做一个项目,我需要通过 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 表格进行编辑吗?

【问题讨论】:

    标签: php google-sheets google-drive-api phpspreadsheet


    【解决方案1】:

    在这种情况下,您可以使用 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 Spreadsheet class methods

    Import to Google Docs types

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-07
      • 2020-03-10
      • 1970-01-01
      • 2016-10-06
      • 1970-01-01
      • 1970-01-01
      • 2022-12-20
      • 1970-01-01
      相关资源
      最近更新 更多