I implemented a WebRequest class for my basic GET and POST requests to URLConnections.
One of the features is submitting files - Now I'd like to calculate and display the progress of the uploading file - but I don't know how to do that:
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");
In this code you see the basic calculation of written bytes to the OutputStream output. But since the request isn't even sent to the server prior opening the InputStream of my connection (or reading the statuscode), this byte counting is completelly useless and only displays the progress of the request preparation.
So my question is: How can I monitor the current state of actually sent bytes to the server? I already checked the Java sources of getInputStream of the corresponding classes (HttpUrlConnection) to try to understand how and when there are actually bytes written to the server... but with no conclusion.
Is there a way to do that without writing my own implementation of the http protocoll?
Thanks
Best regards matt
You have to set conn.setChunkedStreamingMode(-1); // use default chunk size
.
If not, HUC is buffering the whole data just to know which value to set as Content-Length
. You're actually monitoring the buffering process.
As alternative you could calculate the size of your multi-part body (good luck!) and call conn.setFixedLengthStreamingMode(lengthInBytes)
.
You find more on HttpUrlConnection multipart file upload with progressBar
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With