首页 > 解决方案 > 上传 Google Drive 文件 - PNG、JPEG、PDF

问题描述

我目前有一个功能可以成功将 jpg 文件上传到谷歌驱动器。我想知道如何修改该功能,以便我也可以将 pdf、jpg、png 和 docx 文件上传到谷歌驱动器。这是我的代码:

function uploadFiles($filePath) {
    $file = new Google_Service_Drive_DriveFile();
    $file->setName(uniqid().'.jpg');
    $file->setDescription('A test document');
    $file->setMimeType('image/jpeg');

    $data = file_get_contents($filePath);

    $createdFile = $this->service->files->create($file, array(
        'data' => $data,
        'mimeType' => 'image/jpeg',
        'uploadType' => 'multipart'
    ));
}

任何帮助表示赞赏。谢谢。

标签: phpgoogle-drive-api

解决方案


在文件pdf, jpg, png, and docx上传为的情况下pdf, jpg, png, and docx,当使用 Drive API 中的 Files:create 方法上传文件时,似乎会自动检测到文件的 mimeType。我认为在您的情况下,可以使用这种情况。因此,请按如下方式修改您的脚本。

修改后的脚本:

function uploadFiles($filePath) {
    $file = new Google_Service_Drive_DriveFile();
    $file->setName(uniqid());
    $file->setDescription('A test document');

    $data = file_get_contents($filePath);

    $createdFile = $this->service->files->create($file, array(
        'data' => $data,
        'uploadType' => 'multipart'
    ));
}
  • 通过上述修改,对于pdf, jpg, png, and docx,上传的文件具有正确的 mimeType。

推荐阅读