Como baixar o arquivo do httpServlet com Jquery?
Na minha aplicação, um objeto json é criado no lado do cliente. Este objeto é postado em um HttpServlet que cria um arquivo pdf baseado nos dados POST.
O arquivo é enviado de volta ao usuário. A função succes é chamada e os dados do fluxo são registrados. Eu quero, no entanto, que o arquivo seja baixado.
Como conseguir isso?
Meu código de cliente:
$(document).ready(function() {
// when the print button is clicked
$('#exportButton').click(function() {
var tableIdx = performanceDetailTableController.getTableIdx();
var allData = {
"shipTable1":{
"rows":[
{ "latitude":"12323","longitude":"213213"},
{ "latitude":"213213","longitude":"543543"}
]},
"shipTable2":{
"rows":[
{ "latitude":"12323", "longitude":"213213"},
{ "latitude":"213213","longitude":"543543"}
]}
}
var postData = JSON.stringify(allData);
$.ajax({
type : "POST",
url : 'pdfServlet',
contentType: "application/json; charset=utf-8",
data : postData,
async : false,
success : function(data) {
alert("got some data");
console.log(data);
},
});
});
});
E o servlet criando o arquivo:
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
// get the json content
StringBuffer jsonContent = getPostedContent(request);
log.info(jsonContent.toString());
// convert json to pojo's
Tables tables = getTablesFromString(jsonContent);
// create a xml stream
ByteArrayOutputStream xml = new XmlConverter().getXMLSource(tables);
// put the xml on the request
request = setXmlOnRequest(request, xml);
// create pdf data of the pdf-able xml content
ByteArrayOutputStream pdf = new PdfHandler().createPdfDataStream(request);
// response = createResponseheaders(response, request);
response.setContentType("application/pdf");
response.setContentLength(pdf.size());
response.setHeader("Content-disposition", "attachment; filename=test.pdf");
response.setCharacterEncoding("utf-8");
response.getOutputStream().write(pdf.toByteArray());
//close the streams
pdf.close();
response.getOutputStream().close();
}
A saída no log:
%PDF-1.4
%
4 0 obj
<<
/Producer (Apache FOP Version SVN branches/fop-0_95)
/CreationDate (D:20130725162007+02'00')
>>
endobj
5 0 obj
<<
/N 3
/Length 11 0 R
/Filter /FlateDecode
>>
stream
xwTSϽ7PhRHH.*1 J
*MINHA SOLUÇÃO: *
Vejohttp://www.particletree.com/notebook/ajax-file-download-or-not/ para um ponteiro
Eu criei um formulário com um campo oculto:
<button id="exportButton">export</button>
<form id="exportForm" method="post" action="pdfServlet">
<input type="hidden" value="empty" id="pdf_data" name="pdf_data" />
</form>
do que eu mudei o meu jquery post controlador de dados para:
$('#exportButton').click(function() {
var tableIdx = performanceDetailTableController.getTableIdx();
var allData = {
"shipTable1":{
"rows":[
{ "latitude":"12323","longitude":"213213"},
{ "latitude":"213213","longitude":"543543"}
]},
"shipTable2":{
"rows":[
{ "latitude":"12323", "longitude":"213213"},
{ "latitude":"213213","longitude":"543543"}
]}
}
var postData = JSON.stringify(allData);
// put the data on the hidden form field in the export form
$('#pdf_data').val(postData);
// and submit the form
$('#exportForm').submit();
});
agora, quando clico no botão de exportação, o campo oculto no formulário obtém os dados a serem postados e os dados são postados como www-form codificados.
Dessa forma, o servlet pode manipular a solicitação e o arquivo é baixado para o cliente.