首页 > 解决方案 > 上传 Excel 文件 Google Drive API

问题描述

我正在使用 Google Drive API 上传 Excel 文件。我正确地完成了 API 连接。创建文件夹并正确上传excel文件。我可以在我的谷歌驱动器中看到它们。但是,excel文件是空的。我在这里缺少什么?

我的代码如下:

$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;
}

标签: phpexcelgoogle-drive-apispreadsheetgoogle-api-php-client

解决方案


好的,我发现了问题所在。正如我在上面的代码中所写,我有一个相对路径

$path = "uploads/school_info.xlsx";

当我将其更改为这样的完整路径时:

$path = "https://www.example.com/uploads/school_info.xlsx";

一切都按预期工作

谢谢大家的时间


推荐阅读