上传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;
}

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

$path = "uploads/school_info.xlsx";

当我把它改成这样的完整路径时:

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

一切正常

感谢大家抽出时间

答案

我已经成功上传了一个.xlsx文件,其中包含以下代码。显然它和你的非常相似,我只是更改了mimeType并添加了uploadType。文件上传后,我可以从UI版本的Drive访问和查看文件的内容。如果仍然失败,请从这里下载一个示例文件,重复此过程。

代码

$service = new Google_Service_Drive($client);

$file = new Google_Service_Drive_DriveFile();
$file->setName('test.xlsx');
$data = file_get_contents('file_example_XLSX_50.xlsx');

$result = $service->files->create($file, array(
'data' => $data,
'mimeType' => 'application/vnd.ms-excel',
'uploadType' => 'multipart'
));

最新更新