Reputation: 243
I'd like to know if it is possible to write incoming bytes of a HttpServletRequest directly to disk without holding it in memory.
Note that I don't want to wait the entire request to complete, but handle partial data independently. Like chunks.
I'm curently using JBOSS and I get these bytes at ServletInputStream in doPost method only after the entire upload completes. But I want to "read and remove" these bytes from InputStream as I read it. There are huge files being uploaded and I'd like to work in a coordinated flow as shown below:
Is that possible? To work as a raw socket communication... And thus completely avoid OOM.
Upvotes: 2
Views: 449
Reputation: 85781
You can read the data partially by using a chunk (buffer) of the desired size:
BufferedInputStream bis = new BufferedInputStream(yourInputStream);
BufferedOutputStream bos = new BufferedOutputStream(yourFileOutputStream);
final int FILE_CHUNK_SIZE = 1024 * 4; //easier to change to 8 KBs or any other size you want/need
byte[] chunk = new byte[FILE_CHUNK_SIZE];
int bytesRead = 0;
while ((bytesRead = input.read(chunk)) != -1) {
bos.write(chunk, 0, bytesRead);
}
bos.close();
bis.close();
Upvotes: 2