代码来自官方参考,支持在使用的时候发现了一些问题记录下
参考代码
- App.java
package org.example;
import io.tus.java.client.*;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
public class App {
public static void main(String[] args) throws IOException, io.tus.java.client.ProtocolException {
TusClient client = new TusClient();
client.setUploadCreationURL(new URL("http://localhost:1080/files/"));
client.enableResuming(new TusURLMemoryStore());
File file = new File("src/main/resources/my.mp4");
final TusUpload upload = new TusUpload(file);
Map<String,String> medata = new HashMap<>();
medata.put("filename", "my.mp4");
medata.put("filetype", "video/mp4");
System.out.println("Starting upload...");
upload.setMetadata(medata);
TusExecutor executor = new TusExecutor() {
@Override
protected void makeAttempt() throws IOException, io.tus.java.client.ProtocolException {
// First try to resume an upload. If that's not possible we will create a new
// upload and get a TusUploader in return. This class is responsible for opening
// a connection to the remote server and doing the uploading.
TusUploader uploader = client.resumeOrCreateUpload(upload);
// Alternatively, if your tus server does not support the Creation extension
// and you obtained an upload URL from another service, you can instruct
// tus-java-client to upload to a specific URL. Please note that this is usually
// _not_ necessary and only if the tus server does not support the Creation
// extension. The Vimeo API would be an example where this method is needed.
// TusUploader uploader = client.beginOrResumeUploadFromURL(upload, new URL("https://tus.server.net/files/my_file"));
// Upload the file in chunks of 1KB sizes.
// 此处是一个问题,因为我们进行上传的文件比较大,我设置了setChunkSize 为8M,但是tus 会提示offset 409 问题
uploader.setChunkSize(1024*1024*8);
// 解决方法,就是同时也设置setRequestPayloadSize 这样可以确保对于大文件上传没有问题
uploader.setRequestPayloadSize(1024*1024*8);
// Upload the file as long as data is available. Once the
// file has been fully uploaded the method will return -1
do {
// Calculate the progress using the total size of the uploading file and
// the current offset.
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);
// Allow the HTTP connection to be closed and cleaned up
uploader.finish();
System.out.println("Upload finished.");
System.out.format("Upload available at: %s", uploader.getUploadURL().toString());
}
};
executor.makeAttempts();
}
}
import io.tus.java.client.*;
说明
tus-java-client 维护并不是很频繁,同时对于TusURLStore 设计主要提供了基于内存的,如果我们有特殊场景可以自己扩展下
参考资料
https://github.com/tus/tus-node-server
https://github.com/tus/tus-java-client