-
FEATURED COMPONENTS
First time here? Check out the FAQ!
Hey,
I've a problem with the file upload, the uploaded files have the wrong size.
For example:
Original File: 1.527.148 Bytes
File on Server: 1.523.712 Bytes
Here is my code:
UploadEvent event = (UploadEvent) arg0; media = event.getMedia(); if(media.getByteData().length > 10 * 1024 * 1024) { Messagebox.show(err_msg, err_head, Messagebox.OK, Messagebox.ERROR); }else{ String[] data_type = media.getContentType() .split("/"); String file_type = ".apk"; if(data_type.length > 1) { file_type = data_type[1]; } File f = new File("/home/flo/Desktop/"+System.currentTimeMillis()+"."+file_type); if(f.exists()) { f.delete(); } BufferedInputStream in = null; BufferedOutputStream out = null; InputStream fin = media.getStreamData(); in = new BufferedInputStream(fin); OutputStream fout = new FileOutputStream(f); out = new BufferedOutputStream(fout); byte buffer[] = new byte[1024]; int ch = in.read(buffer); while (ch != -1) { out.write(buffer, 0, ch); ch = in.read(buffer); } }
zul:
<button label="Choose file..." width="120px" id="attachBtn" sclass="attachBtn" upload="true" />
Whats wrong here?
Thanks,
flo
You are not closing the streams, so the data is not flushed and in addition you are leaking a file handle.
If you write IO code yourself, always close streams in a finally block!
try { BufferedInputStream in = null; BufferedOutputStream out = null; InputStream fin = media.getStreamData(); in = new BufferedInputStream(fin); OutputStream fout = new FileOutputStream(f); out = new BufferedOutputStream(fout); byte buffer[] = new byte[1024]; int ch = in.read(buffer); while (ch != -1) { out.write(buffer, 0, ch); ch = in.read(buffer); } } finally { if (out != null) { try { out.close(); } catch (IOException e) { } } if (in != null) { try { in.close(); } catch (IOException e) { } } }
OR add Commons IO library to your project and use this much better code:
InputStream in = null; OutputStream out = null; try { in = media.getStreamData(); out = new FileOutputStream(f); IOUtils.copy(in, out); } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); }
Asked: 2012-08-23 11:35:33 +0800
Seen: 133 times
Last updated: Sep 12 '12