0

场景:尝试使用 TUS 协议将 3KB 的文件上传到服务器。如果文件大小超过 1KB,那么文件将被分成 1KB 的块并上传到服务器。

期望:第一次尝试,它应该上传 1KB,然后在第二个循环中再次上传 1KB,然后在第三个循环中上传 1KB。

实际场景:文件上传成功,但到uploader.finish()语句时,抛出以下异常:

Caused by: io.tus.java.client.ProtocolException: response to PATCH request contains no or invalid Upload-Offset header

下面是上传方法:

public void uploadFileTUP(UploadClass uploadClass, File file) {

        try {
            if (System.getProperty("sun.net.http.allowRestrictedHeaders") == null) {
                System.setProperty("sun.net.http.allowRestrictedHeaders", "true");
            }
            byte[] bytes = Files.readAllBytes(file.toPath());

            Map headers = new HashMap();
            headers.put("sastoken", uoloadClass.getToken());
            headers.put("Content-Length", Integer.toString(bytes.length));


            final TusUpload upload = new TusUpload(file);
            TusClient client = new TusClient();
            client.setUploadCreationURL(new URL(uploadClass.getUrl()));
            client.setHeaders(headers);
            client.enableResuming(new TusURLMemoryStore());

            Integer chunkSize = 1024;

            Map metadata = new HashMap();
            metadata.put("name", file.getName());
            metadata.put("chunkSize", String.format("%d", chunkSize));
            metadata.put("contentType", "text/xml");
            upload.setMetadata(metadata);
            logger.log(Level.INFO, "Starting upload...");

            TusExecutor executor = new TusExecutor() {
                @Override
                protected void makeAttempt() throws IOException, ProtocolException {

                    TusUploader uploader = client.resumeOrCreateUpload(upload);
                    uploader.setChunkSize(chunkSize);
                    int result = 0;
                    do {
                        result = uploader.uploadChunk();
                    } while (result > -1);

                    uploader.finish();
                    logger.log(Level.INFO, "Upload finished.");
                }
            };
            executor.makeAttempts();
        }catch (IOException | ProtocolException e){
            throw e;
        }
    }
4

0 回答 0