如何监控文件上传进度?

Sop*_*hie 3 java upload post

我需要将文件上传到服务器并监视它的进度.我需要通知每次发送多少字节.

例如,在下载的情况下,我有:

HttpURLConnection  connection = (HttpURLConnection) m_url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
while ((currentBytes  = stream.read(byteBuffer)) > 0) {                    
    totalBytes+=currentBytes;
    //calculate something...
}
Run Code Online (Sandbox Code Playgroud)

现在我需要为上传做同样的事情.但如果使用

OutputStreamWriter stream = new OutputStreamWriter(connection.getOutputStream());
stream.write(str);
stream.flush();
Run Code Online (Sandbox Code Playgroud)

比我无法获得任何进程通知,关于发送了多少字节(它看起来像自动操作).

有什么建议?

谢谢

Sop*_*hie 5

我使用过 ChannelSocket 对象。该对象允许在访问服务器时进行阻塞读写。所以我使用这个套接字模拟了 HTTP,并且每个写请求都被阻止,直到它完成。这样我就可以跟踪写事务的实际进度。


use*_*421 5

只需设置分块传输模式并监控自己对输出流的写入.

如果不使用分块或固定长度传输模式,则在写入网络之前,所有写入都将写入ByteArrayOutputStream,以便Java可以正确设置Content-Length标头.这就是让你认为它是非阻塞的.事实并非如此.