How to update already existing file in google drive api v3 java

前端 未结 4 693
太阳男子
太阳男子 2021-02-10 19:35

I have tried with the following code... Without any luck...

private void updateFile(Drive service, String fileId) {
        try {
            File file = new Fil         


        
4条回答
  •  隐瞒了意图╮
    2021-02-10 20:02

    For API v3 the solution proposed by Android Enthusiast does not work unfortunately. The issue is with this bit:

     // First retrieve the file from the API.
    File file = service.files().get(fileId).execute();
    

    doing this it will create a File object, with it's ID field being set, when executing the update, itt will throw an exception, since the ID meta field is not editable directly.

    What you can do is simply create a new file:

    File file = new File();
    

    alter the meta you'd like and update file content if required as shown in the example.

    then simply update the file as proposed above:

    // Send the request to the API.
    File updatedFile = service.files().update(fileId, file, mediaContent).execute();
    

    So based a full example would look like this based on Android Enthusiast solution:

    private static File updateFile(Drive service, String fileId, String newTitle,
    String newDescription, String newMimeType, String newFilename, boolean newRevision) {
    try {
    // First create a new File.
    File file = new File();
    
    // File's new metadata.
    file.setTitle(newTitle);
    file.setDescription(newDescription);
    file.setMimeType(newMimeType);
    
    // File's new content.
    java.io.File fileContent = new java.io.File(newFilename);
    FileContent mediaContent = new FileContent(newMimeType, fileContent);
    
    // Send the request to the API.
    File updatedFile = service.files().update(fileId, file, mediaContent).execute();
    
    return updatedFile;
    } catch (IOException e) {
    System.out.println("An error occurred: " + e);
    return null;
    }
    }
    

提交回复
热议问题