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);
	}
}
最終更新:2014年07月25日 11:11