How to monitor transfer rate while uploading files using Google Drive API in Java

I’m working on a Java application that uploads files to Google Drive using their API. I need to track the upload progress and show the transfer speed in real time.

Here’s my current upload code:

// Create file metadata
File fileMetadata = new File();
fileMetadata.setName("sample-report.pdf");
fileMetadata.setDescription("Generated report file");
fileMetadata.setMimeType("application/pdf");

// Prepare file content
java.io.File localFile = new java.io.File("report.pdf");
FileContent content = new FileContent("application/pdf", localFile);

// Execute upload
File uploadedFile = driveService.files().create(fileMetadata, content).execute();
System.out.println("Uploaded file ID: " + uploadedFile.getId());

I want to display the current upload speed every second during the transfer. This means I need to calculate how many bytes are transmitted each second and show it to the user. What’s the best approach to implement this progress tracking feature?

Want to track upload speed with Google Drive API in Java? Use a custom MediaHttpUploaderProgressListener - it’s the best way to capture progress.

Don’t use execute() directly. Go with executeMediaAndDownloadTo() or modify your request to include the progress listener. Build a listener that tracks bytes uploaded and timestamps. Then calculate transfer rate by comparing current upload total against what you measured a second ago.

Make sure you call request.getMediaHttpUploader().setProgressListener() before executing. One gotcha: callbacks won’t happen exactly every second, so you’ll need your own timing logic for updates.

For tiny files, speed calculations aren’t very useful. Check file size first to decide if progress tracking is worth it.

You need to wrap your upload in a resumable session for proper progress tracking. Don’t use the simple execute() method - switch to resumable uploads with MediaHttpUploader instead. Create your request normally, but before executing, grab the uploader instance and configure it for resumable uploads. Set chunk size to something reasonable like 1MB with setChunkSize(). Then add a MediaHttpUploaderProgressListener to capture progress events. In your listener, store the current timestamp and bytes uploaded. Keep a running calculation of bytes transferred per second by comparing against previous measurements. You’ll get callbacks at chunk boundaries, not every second, so maintain a sliding window of recent measurements. One gotcha - the progress listener gives you total bytes uploaded, not incremental chunks. You’ll need to calculate the difference yourself to get actual transfer rates.

use resumable uploads - that’s your solution. break your file into chunks and tap into the progress callbacks. grab timestamps between chunks to calculate transfer speed. just remember to handle network drops since resumable uploads handle interruptions way better than standard uploads.