「DBからバイナリを取得して返すサーブレット」の編集履歴(バックアップ)一覧はこちら
追加された行は緑色になります。
削除された行は赤色になります。
String sql = "select img from " + TABLENAME;
ResultSet rs = pstmt.executeQuery();
byte[] b = null;
while (rs.next()) {
InputStream input = rs.getBinaryStream("img");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
while (true) {
try {
int c = input.read();
if (-1 == c) {
break;
}
baos.write(c);
} catch (IOException e) {
e.printStackTrace();
}
}
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
b = baos.toByteArray();
}
// 結果返信
if (null != b) {
res.setHeader("Content-Disposition", "filename=\"" + filename + "\"");
if (filename.endsWith("png")) {
// 画像
res.setContentType("application/png;");
InputStream in = new ByteArrayInputStream(b);
BufferedImage img = ImageIO.read(in);
ImageIO.write(img, "png", res.getOutputStream());
} else if (filename.endsWith("pdf")) {
// PDF
res.setContentType("application/pdf;");
res.getOutputStream().write(b, 0, b.length);
}
}