java - 使用 Java 和 Google Drive API V3 将文件上传到共享的 Google Drive 位置?
问题描述
我需要使用 Java 将文件上传到共享的 Google Drive 位置(不属于我,而是与我共享)。使用Drive API,我们可以将文件上传到用户拥有的驱动器位置,但还没有找到任何允许上传到共享位置的解决方案。用例类似于应用程序的不同用户需要将文件上传到共享的 Google Drive 位置。关于此主题的其他问题(即this )很少,但没有一个有正确的答案。如果可能,请提供帮助,或者请告知无法以编程方式实现此目的。
解决方案
我在评论者@MateoRandwolf 的帮助下找到了解决方案,因此发布了答案。希望能帮助到你..
根据此文档,该supportsAllDrives=true
参数会通知 Google Drive 您的应用程序旨在处理共享驱动器上的文件。但也提到,该supportsAllDrives
参数有效期至2020年6月1日。2020年6月1日之后,将假设所有应用程序都支持共享驱动器。于是我尝试了 Google Drive V3 Java API,发现目前在V3 API 的 classexecute
方法中默认支持共享驱动器。Drive.Files.Create
附上示例代码片段供其他人参考。此方法uploadFile
使用直接上传将文件上传到 Google 驱动器文件夹并返回上传的 fileId。
public static String uploadFile(Drive drive, String folderId) throws IOException {
/*
* drive: an instance of com.google.api.services.drive.Drive class
* folderId: The id of the folder where you want to upload the file, It can be
* located in 'My Drive' section or 'Shared with me' shared drive with proper
* permissions.
* */
File fileMetadata = new File();
fileMetadata.setName("photo.jpg");
fileMetadata.setParents(Collections.singletonList(folderId));
java.io.File filePath = new java.io.File("files/photo.jpg");
FileContent mediaContent = new FileContent("image/jpeg", filePath);
File file = drive.files().create(fileMetadata, mediaContent)
.setFields("id")
.execute();
System.out.println("File ID: " + file.getId());
return file.getId();
}
推荐阅读
- google-colaboratory - Google Colab 上同一个笔记本的训练时间有时会发生变化
- powershell - 使用 Powershell 调用命令,从外部文件加载 -Computername 变量不起作用
- sqlite - 如何删除数据 React Native SQLite
- postgresql - 多个 DELETE 语句的 Postgres 变量
- tkinter - 如何在 tkinter 的输入框中禁用用户输入?
- google-cloud-platform - 如何查看 Google Cloud Run 应用程序的请求计数(而非速率)?
- android - 从房间 DAO 接口继承
- html - 在 :hover 上设置动画 ::before 内容
- java - 为什么 JSoup 会创建以链接命名的空文件?
- java - Kotlin LocalDateTime 为 Long