Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

private void updateFile(Drive service, String fileId) {
        try {
            File file = new File(); /********/
            final java.io.File fileToUpdate = new java.io.File("D:/Work Data/Files/pdf.pdf");
            FileContent mediaContent = new FileContent("image/pdf", fileToUpdate);
            file = service.files().update(fileId, file, mediaContent).execute();
            System.out.println(fileId);
        } catch (Exception e) {
            if (isDebug) {
                e.printStackTrace();
            }
        }    
    }

also tried with...

 private void updateFile(Drive service, String fileId) {
        try {
            File file = service.files().get(fileId).execute(); /********/
            final java.io.File fileToUpdate = new java.io.File("D:/Work Data/Files/pdf.pdf");
            FileContent mediaContent = new FileContent("image/pdf", fileToUpdate);
            file = service.files().update(fileId, file, mediaContent).execute();
            System.out.println(fileId);
        } catch (Exception e) {
            if (isDebug) {
                e.printStackTrace();
            }
        }    
    }

With every time i execute the code i get the following stacktrace:

java.lang.IllegalArgumentException
    at com.google.api.client.repackaged.com.google.common.base.Preconditions.checkArgument(Preconditions.java:111)
    at com.google.api.client.util.Preconditions.checkArgument(Preconditions.java:37)
    at com.google.api.client.googleapis.media.MediaHttpUploader.setInitiationRequestMethod(MediaHttpUploader.java:872)
    at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.initializeMediaUpload(AbstractGoogleClientRequest.java:237)
    at com.google.api.services.drive.Drive$Files$Update.<init>(Drive.java:3163)
    at com.google.api.services.drive.Drive$Files.update(Drive.java:3113)
    at com.test.DriveTester.updateFile(DriveTester.java:76)
    at com.test.DriveTester.main(DriveTester.java:64)

Can anyone tell what i am doing wrong ? Any sample code for this i.e. updating the content of an already existing file on google drive will be helpful...

like image 524
CoderNeji Avatar asked Jul 23 '16 07:07

CoderNeji


2 Answers

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;
}
}
like image 168
Laszlo Sisa Avatar answered Nov 07 '22 05:11

Laszlo Sisa


I can share javascript code for uploading to an already existing file using v3

    const url = 'https://www.googleapis.com/upload/drive/v3/files/' + fileId + '?uploadType=media';
if(self.fetch){
var setHeaders = new Headers();
setHeaders.append('Authorization', 'Bearer ' + authToken.access_token);
setHeaders.append('Content-Type', mime);

var setOptions = {
    method: 'PATCH',
    headers: setHeaders,
    body:  data 
};
fetch(url,setOptions)
    .then(response => { if(response.ok){
    console.log("save to drive");
    }
            else{
                console.log("Response wast not ok");
            }
              })
    .catch(error => {
    console.log("There is an error " + error.message);
    });
like image 27
s007 Avatar answered Nov 07 '22 05:11

s007