I am developing an Android app which enables the user to upload a file to services like Twitpic and others. The POST upload is done without any external libraries and works just fine. My only problem is, that I can't grab any progress because all the uploading is done when I receive the response, not while writing the bytes into the outputstream. Here is what I do:
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
Then I write the form data to dos, which is not so important here, now. After that I write the file data itself (reading from "in", which is the InputStream of the data I want to send):
while ((bytesAvailable = in.available()) > 0)
{
bufferSize = Math.min(bytesAvailable, maxBufferSize);
byte[] buffer = new byte[bufferSize];
bytesRead = in.read(buffer, 0, bufferSize);
dos.write(buffer, 0, bytesRead);
}
After that, I send the multipart form data to indicate the end of the file. Then, I close the streams:
in.close();
dos.flush();
dos.close();
This all works perfectly fine, no problem so far. My problem is, however, that the whole process up to this point takes about one or two seconds no matter how large the file is. The upload itself seems to happen when I read the response:
DataInputStream inStream = new DataInputStream(conn.getInputStream());
This takes several seconds or minutes, depending on how large the file is and how fast the internet connection. My questions now are: 1) Why doesn't the uplaod happen when I write the bytes to "dos"? 2) How can I grab a progress in order to show a progress dialog during the upload when it all happens at once?
/EDIT: 1) I set the Content-Length in the header which changes the problem a bit, but does not in any way solve it: Now the whole content is uploaded after the last byte is written into the stream. So, this doesn't change the situation that you can't grab the progress, because again, the data is written at once. 2) I tried MultipartEntity in Apache HttpClient v4. There you don't have an OutputStream at all, because all the data is written when you perform the request. So again, there is no way to grab a progress.
Is there anyone out there who has any other idea how to grab a process in a multipart/form upload?