Perform a resumable file upload
mainTo upload a file using the tus protocol, follow these steps:
- Initialize
TusClient: Set the upload creation URL usingsetUploadCreationURL(URL). - Enable Resuming: Use
enableResuming(TusURLStore)(e.g.,TusURLMemoryStore) to store upload URLs so uploads can resume after interruptions. - Create a
TusUpload: Wrap yourFilein aTusUploadobject. - Use
TusExecutor(Recommended): Wrap your upload logic in aTusExecutorto automatically handle retries and exceptions. - Execute Upload: Inside
makeAttempt(), callclient.resumeOrCreateUpload(upload)to get aTusUploader. - Chunked Uploading: Set a chunk size with
uploader.setChunkSize(long)and loop throughuploader.uploadChunk()until it returns-1. - Cleanup: Call
uploader.finish()to close the connection.
// Create a new TusClient instance
TusClient client = new TusClient();
// Configure tus HTTP endpoint
client.setUploadCreationURL(new URL("https://tusd.tusdemo.net/files"));
// Enable resumable uploads by storing the upload URL in memory
client.enableResuming(new TusURLMemoryStore());
File file = new File("./cute_kitten.png");
final TusUpload upload = new TusUpload(file);
System.out.println("Starting upload...");
// Use TusExecutor for automatic retries
TusExecutor executor = new TusExecutor() {
@Override
protected void makeAttempt() throws ProtocolException, IOException {
// Resume or create a new upload
TusUploader uploader = client.resumeOrCreateUpload(upload);
// Upload the file in chunks of 1KB sizes
uploader.setChunkSize(1024);
// Upload until the file is fully uploaded (returns -1)
do {
long totalBytes = upload.getSize();
long bytesUploaded = uploader.getOffset();
double progress = (double) bytesUploaded / totalBytes * 100;
System.out.printf("Upload at %06.2f%%.\n", progress);
} while(uploader.uploadChunk() > -1);
// Cleanup
uploader.finish();
System.out.println("Upload finished.");
System.out.format("Upload available at: %s", uploader.getUploadURL().toString());
}
};
executor.makeAttempts();