Como retornar um download por um servlet

1 resposta
Mikhas

Hey galera!

Alguem sabe me dizer como retorno para meu usuario o download de um arquivo por meio de um servlet?

1 Resposta

Naruffy

Esse é o trecho de um servlet que eu uso para fazer download por ajax.

Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        InputStream inputStream = null;
        byte[] conteudoArquivo = new byte[1000];
        int size = 0;

        try {
            connection = getConnection();
            preparedStatement = connection.prepareStatement(consulta.toString());
            resultSet = preparedStatement.executeQuery();
            resultSet.next();
            String nameFile = resultSet.getString("Localizacao_Arquivo");
            nameFile = nameFile.substring(nameFile.lastIndexOf('\\') + 1);
            nameFile = nameFile.substring(nameFile.lastIndexOf('/') + 1);
            
            inputStream = resultSet.getBinaryStream("Arquivo");
            response.setHeader("Content-Disposition", "attachment;filename=" + nameFile);
            
            // percorre o conteúdo do arquivo passando para o response exibir
            while ((size = inputStream.read(conteudoArquivo)) != -1) {
                response.getOutputStream().write(conteudoArquivo, 0, size);
            }

            response.flushBuffer();
            inputStream.close();

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
           freeConnection(connection);
        }

[]s

Criado 11 de agosto de 2009
Ultima resposta 11 de ago. de 2009
Respostas 1
Participantes 2