byte buf[] = new byte[4096];
BufferedInputStream bis = new BufferedInputStream(request.getInputStream());
FileOutputStream fos = new FileOutputStream(filepath);
int bytesRead = 0;
while((bytesRead = bis.read(buf)) != -1) {
fos.write(buf, 0, bytesRead);}
fos.flush();
fos.close();
bis.close();
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