Using tus-client in Java for efficient file transfers

The tus protocol is an open source protocol that enables resumable file uploads over HTTP. It allows uploads to be paused and resumed without restarting, which is especially useful when dealing with large files or unstable network connections. In this post, we demonstrate how to implement resumable file uploads in Java using the tus-java-client library.
Setting up tus-java-client
Include the dependency in your project's build configuration. Verify that you are using the latest stable version available.
<dependency>
<groupId>io.tus.java.client</groupId>
<artifactId>tus-java-client</artifactId>
<version>0.6.0</version>
</dependency>
Basic usage
Below is a complete example demonstrating how to configure the client, prepare a file for upload, and track progress using automatic retries with TusExecutor:
import io.tus.java.client.TusClient;
import io.tus.java.client.TusExecutor;
import io.tus.java.client.TusUpload;
import io.tus.java.client.TusUploader;
import io.tus.java.client.TusURLMemoryStore;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.net.ProtocolException;
import java.util.Map;
public class TusUploaderExample {
public static void main(String[] args) {
try {
// Create and configure the Tus client.
TusClient client = new TusClient();
client.setUploadCreationURL(new URL("https://tusd.tusdemo.net/files"));
// Enable resumable uploads with an in-memory store.
TusURLMemoryStore store = new TusURLMemoryStore();
client.enableResuming(store);
// Prepare the file for upload.
File file = new File("path/to/your/file.ext");
TusUpload upload = new TusUpload(file);
// Add metadata to the upload if required.
upload.setMetadata(Map.of(
"filename", file.getName(),
"filetype", "application/octet-stream"
));
// Use TusExecutor to handle automatic retries.
TusExecutor executor = new TusExecutor() {
@Override
protected void makeAttempt() throws ProtocolException, IOException {
// Resume or create a new upload.
TusUploader uploader = client.resumeOrCreateUpload(upload);
// Set the chunk size to 5 MB.
uploader.setChunkSize(5 * 1024 * 1024);
// Upload chunks with progress tracking.
do {
long totalBytes = upload.getSize();
long bytesUploaded = uploader.getOffset();
double progress = (double) bytesUploaded / totalBytes * 100;
System.out.printf("Upload progress: %06.2f%% (%d/%d bytes)%n",
progress, bytesUploaded, totalBytes);
} while (uploader.uploadChunk() > -1);
uploader.finish();
System.out.println("Upload completed. URL: " + uploader.getUploadURL());
}
};
executor.makeAttempts();
} catch (ProtocolException e) {
System.err.println("Tus protocol error: " + e.getMessage());
e.printStackTrace();
} catch (IOException e) {
System.err.println("I/O error: " + e.getMessage());
e.printStackTrace();
} catch (Exception e) {
System.err.println("Unexpected error: " + e.getMessage());
e.printStackTrace();
}
}
}
Advanced features
The tus-java-client library offers several advanced configurations for more specialized use cases:
-
Custom Server Support: If your server does not support the Creation extension, you may resume uploads using a predefined URL.
TusUploader uploader = client.beginOrResumeUploadFromURL(upload, new URL("https://tus.server.net/files/my_file"));
-
Proxy Support: Configure a proxy to route your upload requests.
client.setProxy(new java.net.Proxy(java.net.Proxy.Type.HTTP, new java.net.InetSocketAddress("proxy.example.com", 8080)));
-
Custom SSL Configuration: Extend TusClient to apply your own SSLSocketFactory for secure connections. Ensure that your SSLSocketFactory (e.g., mySSLSocketFactory) is properly configured.
@Override public void prepareConnection(HttpURLConnection connection) { super.prepareConnection(connection); if (connection instanceof javax.net.ssl.HttpsURLConnection) { ((javax.net.ssl.HttpsURLConnection) connection).setSSLSocketFactory(mySSLSocketFactory); } }
Best practices
Consider the following best practices when integrating tus-java-client into your application:
- Set an appropriate chunk size that balances performance and resource utilization.
- Monitor upload progress and handle exceptions gracefully to ensure reliability.
- Utilize TusExecutor's automatic retry mechanism to manage intermittent network issues.
- Regularly check for the latest library version to benefit from bug fixes and improvements.
- Configure custom settings (e.g., proxy or SSL) only when necessary, and test them thoroughly in your deployment environment.
Platform compatibility
The tus-java-client library is compatible with both standard Java and Android platforms. For Android-specific features and optimizations, refer to the tus-android-client.
For further details, visit the tus-java-client documentation and the GitHub repository.
In conclusion, implementing resumable file uploads in Java is straightforward with the tus-java-client library. By following these best practices, you can create a robust and efficient file transfer workflow.
For additional insights on advanced file transfer solutions, consider exploring Transloadit's documentation.