Search code examples
javagoogle-apidownloadgoogle-drive-apigoogle-api-java-client

java google drive API unable to download binary file


I have working code to list the files in my Google Drive folder containing binary files but I'm getting an error when trying to download:

GET https://www.googleapis.com/download/drive/v3/files/1udFizffA_0M4jSUBJbDI6uNVdPVhdymW?alt=media
{
  "code" : 403,
  "errors" : [ {
    "domain" : "global",
    "location" : "alt",
    "locationType" : "parameter",
    "message" : "Only files with binary content can be downloaded. Use Export with Docs Editors files.",
    "reason" : "fileNotDownloadable"
  } ],
  "message" : "Only files with binary content can be downloaded. Use Export with Docs Editors files."
}

The relevant code is as follows:

Drive.Files f = driveService.files();
HttpResponse httpResponse = null;
Drive.Files.Get get = f.get(file.getId());
httpResponse = get.executeMedia();

I also tried export using:

httpResponse = f.export(file.getId(),"application/octet-stream").executeMedia();

which didn't work either.

Can someone please help me figure out what I'm missing.


Solution

  • The file.get method does return the file data, however only for binary file types. that is what this error message its telling you.

    Only files with binary content can be downloaded. Use Export with Docs Editors files.

    String fileId = "0BwwA4oUTeiV1UVNwOHItT0xfa2M";
    OutputStream outputStream = new ByteArrayOutputStream();
    driveService.files().get(fileId)
        .executeMediaAndDownloadTo(outputStream);
    

    All other file types those being google docs, google sheets. check this page for more: mimetype

    Need to be exported from the google mime type to a standard mime type. If you check the manage-downloads#java page you will find a documented example of how to use this method.

    String fileId = "1ZdR3L3qP4Bkq8noWLJHSr_iBau0DNT4Kli4SxNc2YEo";
    OutputStream outputStream = new ByteArrayOutputStream();
    driveService.files().export(fileId, "application/pdf")
        .executeMediaAndDownloadTo(outputStream);
    

    The trick with this method is to ensure you are setting the correct mimetype