Can't Grab Progress on Http Post File Upload (Android)

Is there any way to get upload progress correctly with HttpUrlConncetion

I found the explanation on developer document http://developer.android.com/reference/java/net/HttpURLConnection.html

To upload data to a web server, configure the connection for output using setDoOutput(true).
For best performance, you should call either setFixedLengthStreamingMode(int) when the body length is known in advance, or setChunkedStreamingMode(int) when it is not. Otherwise HttpURLConnection will be forced to buffer the complete request body in memory before it is transmitted, wasting (and possibly exhausting) heap and increasing latency.

Calling setFixedLengthStreamingMode() first fix my problem.
But as mentioned by this post, there is a bug in android that makes HttpURLConnection caches all content even if setFixedLengthStreamingMode() has been called, which is not fixed until post-froyo. So i use HttpClient instead for pre-gingerbread.

Android HTTP upload progress for UrlEncodedFormEntity

You can override the #writeTo method of any HttpEntity implementation and count bytes as they get written to the output stream.

DefaultHttpClient httpclient = new DefaultHttpClient();
try {
HttpPost httppost = new HttpPost("http://www.google.com/sorry");

MultipartEntity outentity = new MultipartEntity() {

@Override
public void writeTo(final OutputStream outstream) throws IOException {
super.writeTo(new CoutingOutputStream(outstream));
}

};
outentity.addPart("stuff", new StringBody("Stuff"));
httppost.setEntity(outentity);

HttpResponse rsp = httpclient.execute(httppost);
HttpEntity inentity = rsp.getEntity();
EntityUtils.consume(inentity);
} finally {
httpclient.getConnectionManager().shutdown();
}

static class CoutingOutputStream extends FilterOutputStream {

CoutingOutputStream(final OutputStream out) {
super(out);
}

@Override
public void write(int b) throws IOException {
out.write(b);
System.out.println("Written 1 byte");
}

@Override
public void write(byte[] b) throws IOException {
out.write(b);
System.out.println("Written " + b.length + " bytes");
}

@Override
public void write(byte[] b, int off, int len) throws IOException {
out.write(b, off, len);
System.out.println("Written " + len + " bytes");
}

}

Flutter Monitor FileUpload progress using the http package

Take a look at this example on GitHub. It demonstrates how you can access the current upload progress of your file.

File Upload with Java (with progress bar)

I ended up stumbling across an open source Java uploader applet and found everything I needed to know within its code. Here are links to a blog post describing it as well as the source:

Article

Source Code



Related Topics



Leave a reply



Submit