You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

调用com.google.api.services.drive.model.File.getName()返回null求助

问题解决:Google Drive API上传后file.getName()返回null

问题根源在你调用API时的setFields("id")配置:

  • Google Drive API使用字段掩码机制,setFields()定义了API响应需要返回的字段。你只指定了id字段,所以返回的com.google.api.services.drive.model.File对象里只有id有值,包括name在内的其他字段都会是null。
  • 你在Google Drive能看到文件名,是因为上传时fileMetadata里已经设置了文件名,但API响应并未将该字段返回给你。

修复方法很简单,把需要的字段加入setFields()中,比如同时请求id和name:

com.google.api.services.drive.model.File file = googleDriveService.files().create(fileMetadata, fileContent)
                                        .setFields("id,name")
                                        .execute();

如果需要返回更多字段(如创建时间、文件大小等),可以用逗号分隔添加;若要返回所有字段(不推荐生产环境使用,会增大响应体积),可以写成:

.setFields("*")

修改后再调用file.getName()就能获取到预期的"foo.dat"了。

内容的提问来源于stack exchange,提问作者Hong

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 11:54:54