|
| 1 | +package io.tus.java.example; |
| 2 | + |
| 3 | +import java.io.File; |
| 4 | +import java.net.URL; |
| 5 | + |
| 6 | +import io.tus.java.client.TusClient; |
| 7 | +import io.tus.java.client.TusURLMemoryStore; |
| 8 | +import io.tus.java.client.TusUpload; |
| 9 | +import io.tus.java.client.TusUploader; |
| 10 | + |
| 11 | +public class Main { |
| 12 | + public static void main(String[] args) { |
| 13 | + try { |
| 14 | + // Create a new TusClient instance |
| 15 | + TusClient client = new TusClient(); |
| 16 | + |
| 17 | + // Configure tus HTTP endpoint. This URL will be used for creating new uploads |
| 18 | + // using the Creation extension |
| 19 | + client.setUploadCreationURL(new URL("http://localhost:1080/files/")); |
| 20 | + |
| 21 | + // Enable resumable uploads by storing the upload URL in memory |
| 22 | + client.enableResuming(new TusURLMemoryStore()); |
| 23 | + |
| 24 | + // Open a file using which we will then create a TusUpload. If you do not have |
| 25 | + // a File object, you can manually construct a TusUpload using an InputStream. |
| 26 | + // See the documentation for more information. |
| 27 | + File file = new File("./example/assets/prairie.jpg"); |
| 28 | + TusUpload upload = new TusUpload(file); |
| 29 | + |
| 30 | + // First try to resume an upload. If that's not possible we will create a new |
| 31 | + // upload and get a TusUploader in return. This class is responsible for opening |
| 32 | + // a connection to the remote server and doing the uploading. |
| 33 | + TusUploader uploader = client.resumeOrCreateUpload(upload); |
| 34 | + |
| 35 | + System.out.println("Starting upload..."); |
| 36 | + |
| 37 | + // Upload the file in chunks of 1KB as long as data is available. Once the |
| 38 | + // file has been fully uploaded the method will return -1 |
| 39 | + while (uploader.uploadChunk(1024) > -1) { |
| 40 | + // Calculate the progress using the total size of the uploading file and |
| 41 | + // the current offset. |
| 42 | + long totalBytes = upload.getSize(); |
| 43 | + long bytesUploaded = uploader.getOffset(); |
| 44 | + double progress = (double) bytesUploaded / totalBytes * 100; |
| 45 | + |
| 46 | + System.out.printf("Upload at %06.2f%%.\n", progress); |
| 47 | + } |
| 48 | + |
| 49 | + // Allow the HTTP connection to be closed and cleaned up |
| 50 | + uploader.finish(); |
| 51 | + |
| 52 | + System.out.println("Upload finished."); |
| 53 | + System.out.format("Upload available at: %s", uploader.getUploadURL().toString()); |
| 54 | + } catch(Exception e) { |
| 55 | + e.printStackTrace(); |
| 56 | + } |
| 57 | + |
| 58 | + } |
| 59 | +} |
0 commit comments