pdfファイルをOutputStreamでダウンロードさせる方法メモ

protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException{
	try {
		response.reset();
		response.setHeader("Content-Disposition", "inline; filename=aaa.pdf");
		response.setContentType("application/pdf");
		BufferedInputStream in = null;
		byte[] buf;
		in = new BufferedInputStream(
				new FileInputStream("x:\\xxx\\aaa.pdf")
		);
		buf = new byte[in.available()];
		in.read(buf);
		OutputStream out = response.getOutputStream();
		out.write(buf);
		out.flush();					

		in.close();
		out.close();
	} catch (Exception e) {
		throw new IllegalStateException(e);
	}
}

で、ファイルがでかくて、ちょっとづつレスポンスに返したい場合は、以下のようにする。

buf = new byte[1024];
int bytedata = 0;
while ((bytedata = in.read(buf, 0, buf.length)) > -1) {
	out.write(buf, 0, bytedata);
}
out.flush();