I have a java applet for uploading files to server.
I want to display the % of data sent but when I use ObjectOutputStream.write()
it just writes to the buffer, does not wait until the data has actually been sent. How can I achieve this.
Perhaps I need to use thread synchronization or something. Any clues would be most helpful.

- 5,753
- 72
- 57
- 129

- 341
- 2
- 5
- 19
-
1Look for existing code that does this. Don't write you own – Pyrolistical Mar 31 '10 at 18:56
2 Answers
Don't use ObjectOutputStream
. It's for writing serialized Java objects, not for writing raw binary data. It may indeed block the stream. Rather just write directly to the OutputStream
of the URL connection.
That said, the code looks pretty overcomplicated. Even after re-reading several times and blinking my eyes countless times, I can't get it right. I suggest you to send those files according the multipart/form-data
encoding with help of Commons HttpClient. You can find here a basic code example. You just have to modify Part[] parts
to include all the files. The servlet on the other side can in turn use Commons FileUpload to parse the multipart/form-data
request.
To calculate the progress, I'd suggest to pick CountingOutputStream
of Commons IO. Just wrap the OutputStream
with it and write to it.
Update: if you don't like to ship your applet with more 3rd party libraries (which I imagine is reasonable), then have a look at this code snippet (and the original question mentioned as 1st link) how to create a multipart/form-data
body yourself using URLConnection
.
-
Thanks a lot. I know the code is complicated. I haven't written it myself since I just got this code and am trying to make some new stuff in it. I'll give a try at your examples. By the way, I just wanted to congratulate you on your blog for it helped me a lot with JSF! – user295744 Apr 01 '10 at 09:03
-
I actually need to use ObjectOutputStream because I'm sending a HashMap before the code I presented here... – user295744 Apr 01 '10 at 09:38
-
Thank you. Well, that's the nature of `ObjectOutputStream`. It can't send the data byte by byte, it can only send the data in chunks/objects. Either live with it or drop it and go ahead with sending a "normal" HTTP multipart/form-data request. – BalusC Apr 01 '10 at 12:17
What I was looking for was actually:
setFixedLengthStreamingMode(int contentLength)
This prevents any internal buffering allowing me know exactly the amount of data being sent.

- 341
- 2
- 5
- 19