如何在PHP调用Google Drive API时配置支持pdf、doc/docx的多种MIME类型
实现方法
核心思路是取消硬编码的固定MIME类型,根据文件后缀自动匹配pdf、doc、docx对应的标准MIME值,未匹配到的格式可回退为默认的application/octet-stream。
首先整理你需要支持的格式对应的MIME映射关系:
- pdf后缀对应MIME值:
application/pdf - doc后缀对应MIME值:
application/msword - docx后缀对应MIME值:
application/vnd.openxmlformats-officedocument.wordprocessingml.document
代码修改示例
你可以参考以下逻辑调整你的上传代码:
// 定义允许的格式MIME映射 $allowedMimes = [ 'pdf' => 'application/pdf', 'doc' => 'application/msword', 'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' ]; // 获取文件后缀 $extension = strtolower(pathinfo($file_path, PATHINFO_EXTENSION)); // 匹配对应MIME,匹配不到则用默认值 $mimeType = isset($allowedMimes[$extension]) ? $allowedMimes[$extension] : 'application/octet-stream'; $result = $service->files->create( $file, array( 'data' => file_get_contents($file_path), 'mimeType' => $mimeType, ) );
可选优化
如果需要避免文件后缀伪造的问题,可以使用PHP内置的finfo扩展检测文件真实内容对应的MIME类型,示例如下:
$finfo = new Finfo(FILEINFO_MIME_TYPE); $mimeType = $finfo->file($file_path);
内容的提问来源于stack exchange,提问作者SA Ira
相关产品推荐
相关产品推荐

