/ Published in: Java
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
// set response headers response.setContentType((mimeType != null) ? mimeType : "application/octet-stream"); response.setContentLength((int) file.length()); // read and write file ServletOutputStream op = response.getOutputStream(); // 128 KB buffer int bufferSize = 131072; FileChannel fileChannel = fileInputStream.getChannel(); // 6x128 KB = 768KB byte buffer ByteBuffer bb = ByteBuffer.allocateDirect(786432); byte[] barray = new byte[bufferSize]; int nRead, nGet; try { while ((nRead = fileChannel.read(bb)) != -1) { if (nRead == 0) continue; bb.position(0); bb.limit(nRead); while (bb.hasRemaining()) { // read bytes from disk bb.get(barray, 0, nGet); // write bytes to output op.write(barray); } bb.clear(); } e.printStackTrace(); } finally { bb.clear(); fileChannel.close(); fileInputStream.close(); } }