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

How to get the content length(aka file size) from the MediaHttpDownloader? drive file.getSize() always return null


I want to download a file from Gdrive. So I m using drive API v3 (java).

here the code snippet.

Drive.Files.Get request = driveService.files().get(fileId);
// Get the file metadata
File downloadFile = request.execute();
Long fileSize = downloadFile.getSize(); // always returns null.

OutputStream out = new FileOutputStream(fileName);

request.getMediaHttpDownloader().setProgressListener(
                            new DriveDownloadProgressListener(messageQueue));
request.executeMediaAndDownloadTo(out);

here downloadFile.getSize() always returns null. Is there any way to get the file size from the MediaHttpDownloader?


Solution

  • I have to add required fields myself in the request.

    like this

    
    Drive.Files.Get request = driveService.files().get(fileId).setFields("size");
    File file = request.execute(); // contains only size field.Other fields will be empty
    
    

    then execute and get the expected response(It only send fields setted by yourself)

    For example, if you need name and size of the file.

    Drive.Files.Get request = driveService.files().get(fileId).setFields("name,size"); // name and size
    File file = request.execute(); // contains only name and size field.Other fields will be empty(respective get methods will return null only)