Search code examples
javagoogle-drive-apifilesize

Get size of files using Google drive API


I am trying to list files from google drive along with their sizes for my app & below is the how i tried getting the size

File file = service.files().get(file.getId()).setFields("size").execute();
file.getSize()

I came to know that the size obtained from this call is not right as google drive only populates file size for files apart from google docs, sheet Get size of file created on Google drive using Google drive api in android

Also I tried determining file's size by making http GET to webContentLink & checking the Content-Length header like below

HttpURLConnection conn = null;
        String url = "https://docs.google.com/a/document/d/1Gu7Q2Av2ZokZZyLjqBJHG7idE1dr35VE6rTuSii36_M/edit?usp=drivesdk";
        try {
            URL urlObj = new URL(url);
            conn = (HttpURLConnection) urlObj.openConnection();
            conn.setRequestMethod("HEAD");
            conn.getInputStream();
            System.out.println(conn.getContentLength());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            conn.disconnect();
        }

But in this case , the file size is not correct as it comes out be very large

Is there any way I can determine the file size ?


Solution

  • Found the solution to the problem. For files uploaded to google drive, file size can be determined with file.getSize() call. For Google apps files such as doc, spreadsheet etc file.getSize() will return null as they don't consumer any space in drive. So as a hacky way, I am exporting as a pdf & determining the size. Below is the code for that

    try {
                Drive service = new Drive.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential)
                            .setApplicationName("xyz")
                            .build();
                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                service.files().export(fileId, "application/pdf")
                    .executeMediaAndDownloadTo(outputStream);
                int fileSize = outputStream.toByteArray().length;
            } catch (Exception ex) {
    
            }