首页 > 解决方案 > 使用 Java 和 Google Drive API V3 将文件上传到共享的 Google Drive 位置?

问题描述

我需要使用 Java 将文件上传到共享的 Google Drive 位置(不属于我,而是与我共享)。使用Drive API,我们可以将文件上传到用户拥有的驱动器位置,但还没有找到任何允许上传到共享位置的解决方案。用例类似于应用程序的不同用户需要将文件上传到共享的 Google Drive 位置。关于此主题的其他问题(即this )很少,但没有一个有正确的答案。如果可能,请提供帮助,或者请告知无法以编程方式实现此目的。

标签: javagoogle-apigoogle-drive-apigoogle-api-java-clientgoogle-drive-android-api

解决方案


我在评论者@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();
}

推荐阅读