mat*_*att 5 java upload outputstream status httpurlconnection
我为URLConnections的基本GET和POST请求实现了一个WebRequest类.
其中一个功能是提交文件 - 现在我想计算并显示上传文件的进度 - 但我不知道如何做到这一点:
for (KeyFilePair p : files) {
if (p.file != null && p.file.exists()) {
output.writeBytes("--" + boundary + "\n");
output.writeBytes("Content-Disposition: form-data; name=\""
+ p.key + "\"; filename=\"" + p.file.getName() + "\"\n");
output.writeBytes("Content-Type: " + p.mimetype
+ "; charset=UTF-8\n");
output.writeBytes("\n");
InputStream is = null;
try {
long max = p.file.length();
long cur = 0;
is = new FileInputStream(p.file);
int read = 0;
byte buff[] = new byte[1024];
while ((read = is.read(buff, 0, buff.length)) > 0) {
output.write(buff, 0, read);
output.flush();
cur += read;
if (monitor != null) {
monitor.updateProgress(cur, max);
}
}
} catch (Exception ex) {
throw ex;
} finally {
if (is != null) {
try {
is.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}
}
output.writeBytes("\n--" + boundary + "--\n");
Run Code Online (Sandbox Code Playgroud)
在此代码中,您将看到OutputStream输出的写入字节的基本计算.但由于在打开连接的InputStream(或读取状态代码)之前,请求甚至没有发送到服务器,因此该字节计数完全没用,只显示请求准备的进度.
所以我的问题是:如何监控实际发送到服务器的字节的当前状态?我已经检查了相应类(HttpUrlConnection)的getInputStream的Java源代码,试图了解实际上字节写入服务器的方式和时间......但没有结论.
有没有办法在不编写我自己的http协议实现的情况下做到这一点?
谢谢
最好的问候亚光
你必须设置conn.setChunkedStreamingMode(-1); // use default chunk size.
如果没有,HUC正在缓冲整个数据只是为了知道要设置的值Content-Length.你实际上在监控缓冲过程.
作为替代方案,您可以计算多部分身体的大小(祝你好运!)并致电conn.setFixedLengthStreamingMode(lengthInBytes).
您可以在progressBar上找到有关HttpUrlConnection多部分文件上传的更多信息