【问题标题】:Track file upload progress with WriterInterceptor使用 WriterInterceptor 跟踪文件上传进度
【发布时间】:2016-09-28 11:32:52
【问题描述】:

我正在尝试创建一个进度条,用于显示从带有球衣 2.22 的客户端上传文件的进度。我尝试关注此answer 并使用WriteInterceptorOutputStream 包装成CountingOutputStream

现在的问题是,一旦文件上传开始,完整的字节数就会在一秒钟内打印到控制台。但是在上传完成之前很长一段时间没有任何反应。

我很确定我只是在使用此解决方案跟踪写入客户端缓冲区的字节(而不是真正发送到主机的字节)。

所以我的问题是:我在这里误解了什么吗?还是根本无法跟踪从客户端发送到主机的字节?

public class UploadMonitorInterceptor implements WriterInterceptor {

    @Override
    public void aroundWriteTo(WriterInterceptorContext context) throws IOException, WebApplicationException {
        final OutputStream os = context.getOutputStream();                    

        context.setOutputStream(new MyCountingOutputStream(os));

        context.proceed();          
    }
}

MyCountingOutputStream 类:

public class MyCountingOutputStream extends CountingOutputStream {
    public MyCountingOutputStream(OutputStream out) {
        super(out);
    }

    @Override
    public void write(byte[] b,int st,int end) throws IOException {
        super.write(b,st,end);
        System.out.println("ByteCount:"+end);
    }
}

【问题讨论】:

  • Writer 拦截器用于出站。 ReaderInterceptor 用于入站。
  • @peeskillet 是的,没错。但我想从客户端上传一个文件到主机,并在客户端跟踪上传进度。所以 WriterInterceptor 应该是正确的..还是不正确?
  • 哦。我不知道,我从来没有实施过这样的事情。将是我必须做一些深入思考的事情:-)
  • @peeskillet 哦,我认为获取文件上传进度是一件非常基本的事情:/

标签: java jersey


【解决方案1】:

我终于能够解决我的问题。实际上,我只是将流的写入命令跟踪到缓冲区中。我现在所做的是将chunkedStreamingMode 设置为1024。然后我只需要将以下函数接收到的提供程序设置为客户端的连接器。

private static HttpUrlConnectorProvider buildHttpUrlConnectorProvider(){
             HttpUrlConnectorProvider.ConnectionFactory factory = new HttpUrlConnectorProvider.ConnectionFactory() {
                    @Override
                    public HttpURLConnection getConnection(URL url) throws IOException {
                        HttpURLConnection result = (HttpURLConnection) url.openConnection();
                        result.setChunkedStreamingMode(1024);
                        return result;
                    }
                };
             return new HttpUrlConnectorProvider().connectionFactory(factory);
        }

据我了解,如果设置了chunkedStreamingMode,缓冲将被禁用。

【讨论】:

    猜你喜欢
    • 2023-03-31
    • 1970-01-01
    • 2014-11-15
    • 1970-01-01
    • 2012-01-01
    • 1970-01-01
    • 2012-08-18
    • 2016-05-19
    • 2014-06-03
    相关资源
    最近更新 更多