Galera.
Estou montando uma aplicação WEB que retorna para o usuário um arquivo PDF que é aberto no próprio browser.
Chamando o servlet através do submit do form já está rolando.
Porém estou querendo adaptar para rodar com ajax, ou seja, fazer a requisição e tratar a resposta com o ajax,
pois assim poderei colocar um gif de progresso para que a tela não fique estática enquanto o arquivo é processado.
Abaixo as principais partes do código:
Servlet:
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException
{
// Aqui existem funcões e que buscam os dados no banco tendo como parâmetro o código,
// e geram o arquivo pdf
try
{
File file = new File("c:\\temp\\arquivo.pdf");
arquivo = fileToByte(file);
}
catch (Exception e)
{
e.printStackTrace();
}
// Abrir PDF no Browser
response.setContentType("application/pdf");
response.setContentLength(arquivo.length);
ServletOutputStream ouputStream = response.getOutputStream();
ouputStream.write(arquivo, 0, arquivo.length);
ouputStream.flush();
ouputStream.close();
}
Index.htm :
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<link href="css/css.css" type="text/css" rel="stylesheet" />
<script type="text/javascript" language="javascript" src="js/js.js"></script>
<title></title>
</head>
<body>
<label id="label">Código do Boleto:</label>
<input type="text" name="edtcodigo" id="edtcodigo" size="15">
<a id="a" href="javascript:ajaxRequest();"><img id="img" src="img/botao_gerar.png"></a>
</body>
</html>
function ajaxRequest() {
if (window.XMLHttpRequest) // Firefox, Safari, Opera, etc
{
ajax_req = new XMLHttpRequest();
} else if (window.ActiveXObject) // Internet Explorer
{
try
{
ajax_req = new ActiveXObject("Msxml2.XMLHTTP");//Versões mais novas
} catch (e)
{
try
{
ajax_req = new ActiveXObject("Microsoft.XMLHTTP");//Versão mais antiga
} catch (e)
{
}
}
}
if (!ajax_req) {
alert("Problemas com a requisição!");
return false;
}
ajax_req.onreadystatechange = processarRequisicao;
ajax_req.open('GET','http://localhost:8080/MeuServlet/ajax?edtcodigo='+ document.getElementById("edtcodigo").value, true);
ajax_req.send(null);
}
function processarRequisicao()
{
if (ajax_req.readyState == 4)
{
if (ajax_req.status == 200)
{
document.getElementById("edtcodigo").value = "";
document.getElementById("edtcodigo").focus;
}
}
}
Porém o arquivo não abre no browser.
Como eu posso abrir o pdf no browser através do ajax?
Valews...