Java上传docx转Google Docs报错:无效MIME类型问题求助
解决Google Drive上传Docx并转换为Google Docs的MIME类型错误
错误原因
你错误地将上传媒体的MIME类型设置为Google Docs的格式标识(application/vnd.google-apps.document),但Drive API要求:
- 上传时的媒体MIME类型必须是原始文件的真实类型(Docx对应的是
application/vnd.openxmlformats-officedocument.wordprocessingml.document) - 要触发格式转换,需在文件元数据中设置目标格式的MIME类型
修改后的代码
Drive service = getDriveService(); com.google.api.services.drive.model.File fileMetadata = new com.google.api.services.drive.model.File(); fileMetadata.setName("sample"); // 在元数据中设置目标格式,触发转换为Google Docs fileMetadata.setMimeType("application/vnd.google-apps.document"); java.io.File filePath = new java.io.File("C:\\Users\\sample.docx"); // 上传时使用原始Docx文件的MIME类型 String originalType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"; com.google.api.services.drive.model.File file = service.files().create(fileMetadata, new FileContent(originalType, filePath)) .setFields("id") .execute(); System.out.println("File ID: " + file.getId());
关键说明
- 元数据的
mimeType字段告诉Drive API你希望将上传的文件转换为指定格式(这里是Google Docs) FileContent的MIME类型必须匹配你实际上传的文件类型,否则会触发invalidContentType错误- 确保你的Drive服务账号拥有创建文件的权限,且目标路径下的docx文件存在且可读取
内容的提问来源于stack exchange,提问作者Aravinthram S
相关产品推荐
相关产品推荐

