せっかく書いたんだから公開しちゃえシリーズ。
PDFファイルっつーより、バイナリファイルをダウンロードさせるサンプル。
質問を受けたので書いてみた。ソースはRead more。
package pkg;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class PdfDownloadServlet extends HttpServlet {
private static String FILE_PATH = "/path/to/test.pdf";
private static int IO_LENGTH = 1024;
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
InputStream in = null;
OutputStream out = null;
try {
in = new BufferedInputStream(new FileInputStream(FILE_PATH));
out = response.getOutputStream();
response.setContentType("application/pdf");
response.setHeader("Content-Disposition", "attachment;filename=\"hoge.pdf\"");
int data;
byte[] b = new byte[IO_LENGTH];
while ((data = in.read(b, 0, IO_LENGTH)) != -1) {
out.write(b, 0, data);
}
} finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}