Tenho uma imagem no banco de dados, a qual DEVERIA ser exibida na página, mas o servlet não a carrega.
Tenho as seguintes classes e métodos.
Classe auxiliar para carregar o binário
public final class Auxiliar{
public static byte[] carregaBinario( InputStream in, int tamanhoBytes ) throws IOException{
ByteArrayOutputStream bou = new ByteArrayOutputStream();
int bytesLidos = -1;
byte[] buffer = new byte[tamanhoBytes];
while ( (bytesLidos = in.read( buffer, 0, tamanhoBytes )) > 0 )
{
bou.write(buffer, 0, bytesLidos);
}
byte[] retorno = bou.toByteArray();
bou.close();
return retorno;
}
}
A classe que obtém os dados do banco de dados
public class ImagemBean{
private int id;
private InputStream binario;
// getters e setters omitidos
}
public ImagemDAO{
private ImagemBean populaBean(ResultSet rs) throws Exception{
ImagemBean bean = new ImagemBean();
imagemBean.setId(rs.getInt("id"));
imagemBean.setBinario(new ByteArrayInputStream( Auxiliar.carregaBinario(rs.getBinaryStream("binario"), 1024) ));
return imagemBean;
}
public ImagemBean obter( int id ){
// Connection e Statement omitidos (executarConsulta)
ResultSet rs = this.executarConsulta( "select * from imagem where id = "+ id );
ImagemBean bean = null;
if( rs.next() ){
bean = populaBean( rs );
}
return bean;
}
}
E, por fim, o Servlet (uma Action do Struts, mas até aí…!!)
public class ImagemAction extends Action {
private void carregarImagem( HttpServletRequest request, HttpServletResponse response ) throws Exception
{
int id = Integer.parseInt( request.getParameter("id") );
ImagemDAO dao = new ImagemDAO();
ImagemBean bean = dao.obter( id );
InputStream entrada = bean.getBinario();
// definição de parâmetros
try
{
// carrega o arquivo
response.setContentType("application/octet-stream");
response.getOutputStream().write( Auxiliar.carregaBinario( entrada, 1024 ) );
response.getOutputStream().close();
entrada.close();
}
catch( IOException ioE )
{
// tratamento de erro
// nenhuma Exception é gerada
}
}
}
No fim das contas a imagem não é carregada.
Alguma sugestão ou erro?