Search code examples
javagoogle-apigoogle-drive-apigoogle-api-java-clientgoogle-drive-android-api

Upload a file to shared google drive location using Java with Google Drive API V3?


I need to upload files to a shared Google Drive location(which is not owned by me, rather shared with me) using Java. Using the Drive APIs, We can upload files to a drive location which the user owns, But have not found any solution to allow upload to a shared location. The use case is something like different users of an application need to upload files to a shared Google Drive location. There are few other questions( i.e this) asked on this topic, but none of them has proper answer. Please help if it is possible or please inform it is not possible to achieve this programmatically.


Solution

  • I found the solution with the help of fellow commenter @MateoRandwolf, Hence posting the answer. Hope it helps..

    As per this documentation, the supportsAllDrives=true parameter informs Google Drive that your application is designed to handle files on shared drives. But it is also mentioned that the supportsAllDrives parameter will be valid until June 1, 2020. After June 1, 2020, all applications will be assumed to support shared drives. So I tried with the Google Drive V3 Java API, and found that shared drives are currently supported by default in the execute method of Drive.Files.Create class of V3 APIs. Attaching a sample code snippet for others reference. This method uploadFile uploads a file to Google drive folder using direct upload and returns the uploaded 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();
    }