Just a note

Thursday, March 8, 2012

Save File Stream to Local Dir

9:27 AM Posted by wardah kaddihani , No comments
I got this code from stackoverflow. Then I modified it a bit and now I can save file stream to my server directory.

  1. byte buf[] = new byte[4096];
  2. BufferedInputStream bis = new BufferedInputStream(request.getInputStream());
  3. FileOutputStream fos = new FileOutputStream(filepath);
  4. int bytesRead = 0;
  5. while((bytesRead = bis.read(buf)) != -1) {
  6. fos.write(buf, 0, bytesRead);}
  7. fos.flush();
  8. fos.close();
  9. bis.close();
What I learn:
line 1 
shows buffer of bytes with size 4096. change it to certain number so it will be package of KB (1024 for 1 KB), number above shows that we have 4 KB buffer.

line 2
we use BufferedInputStream to read a stream of file in more efficient manners (rather than read a byte each time).
since we get POST request contains a stream of file, we use request.getInputStream() to catch the stream (something like php://input).
note: it's a different case if we use form to upload a file (i don't think we can do this the same way, since php://input also not available with enctype="multipart/form-data" )

line 3
we use FileOutputStream to write stream of file to a certain path in our directory.

line 5-6
write the contain of buffer until there's no data left to read in buffer

line 7
force the outputstream to really write it all

line 8-9
close all stream

0 comments:

Post a Comment