Search code examples
androidgoogle-drive-apigoogle-drive-android-api

How to upload and download files from Google Drive (using Rest Api v3)


I am using the following java code to upload a file from my Android app to Google Drive using the REST Api v3:

String UploadFileToGoogleDrive(String sFullPath, String sFileName, String sParentFolderId) {               
    com.google.api.services.drive.model.File fileMetadata = new com.google.api.services.drive.model.File();
    fileMetadata.setName(sFileName);
    fileMetadata.setParents(Collections.singletonList(sParentFolderId));
    java.io.File filePath = new java.io.File(sFullPath);
    FileContent mediaContent = new FileContent(null, filePath);
    try {
        com.google.api.services.drive.model.File file = googleDriveService.files().create(fileMetadata, mediaContent)
                .setFields("id, parents")
                .execute();
        return file.getId();
    } catch (IOException e) {            
        return null;
    }       
}

And I use this code to download the file:

boolean DownloadFileFromGoogleDrive(String sFileId, String sDestinationPath) {       
    try {
        FileOutputStream oFileOutputStream = new FileOutputStream(new File(sDestinationPath));
        googleDriveService.files().get(sFileId).executeAndDownloadTo(oFileOutputStream);
        oFileOutputStream.close();
        return true;
    } catch (IOException e) {
        return false;
    }
}

The file gets uploaded (apparently) but, when I download it, it is not readable. The size is much smaller, too. I need to upload images and other files like my own app settings (which is not a mime type) that is why I set null in this line:

FileContent mediaContent = new FileContent(null, filePath);

I have also have tried with "image/jpeg" but I got same results. The downloaded file is not readable.

Any ideas of what I am doing wrong? I cannot find much documentation about Google Drive v3 and Android with Java.


Solution

  • Ok, solved. The problem was in the DownloadFileFromGoogleDrive function:

    boolean DownloadFileFromGoogleDrive(String sFileId, String sDestinationPath) {       
        try {
            OutputStream oOutputStream = new FileOutputStream(sDestinationPath);
            googleDriveService.files().get(sFileId).executeMediaAndDownloadTo(oOutputStream);
            oOutputStream.flush();
            oOutputStream.close();
            return true
        } catch (IOException e) {
            return false;
        }
    }