tags:

views:

75

answers:

2

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.

Thanks

+4  A: 

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.

BalusC
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!
I actually need to use ObjectOutputStream because I'm sending a HashMap before the code I presented here...
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
+1  A: 

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.