PDA

View Full Version : J2EE servlet returns PDF. How do I present the download dialogue



OuZo
15 Dec 2010, 1:49 AM
Hi,

I have a J2EE servlet that writes a PDF to the output stream.


sos = response.getOutputStream();
response.setContentType("application/pdf");
response.setHeader("Content-disposition", "attachment; filename=" + staticReportBridge.getName() + ".pdf;");

response.setContentLength(baosPDF.size());
baosPDF.writeTo(sos);
sos.flush();
sos.close();




In my js file, there is a button that calls the servlet.



Ext.Ajax.request({
//specify servlet url
url: 'PDFStaticReport?action=PDFStaticReport',
mediaType :'PDF',
isUpload: true,
params : {
'SR_ID': rec
},
//use post
method: 'POST',
//method will run if server returns success message
success : function(result, request) {

},
//method will run if server returns failure message
failure: function ( result, request) {
Ext.MessageBox.alert('Failure','Static Report PDF Preview Failed');
}
});//ajax request


In fire bug, I can see if success : function(result, request) the result.responseText is the binary PDF data.
How can I get the browsers dialogue box to save the PDF to pop up?

Thanks

Condor
15 Dec 2010, 2:42 AM
You can't use an Ext.Ajax.request for this.

Instead, you could use Animal's LinkButton or my Ext.ux.Report user extension.

(and you can't have a success handler when using Content-disposition:attachment)

OuZo
15 Dec 2010, 7:16 AM
Thanks Condor,

I added this to the top of my JS file:



Ext.ux.Report = Ext.extend(Ext.Component, {
autoEl: {tag: 'iframe', cls: 'x-hidden', src: Ext.SSL_SECURE_URL},
load: function(config){
this.getEl().dom.src = config.url + (config.params ? '?' + Ext.urlEncode(config.params) : '');
}
});
Ext.reg('ux.report', Ext.ux.Report);


My button in the js file looks like this:



{
text: 'Preview',
iconCls: 'preview',
id: 'report',
xtype: 'ux.report',
handler: function() {

// get the combobox id
var rec = staticReportBridgeNameCombo.getValue();
if (rec == "") {
Ext.message.msg('Notice','Select Static Report First');
} else {
Ext.message.msg('Notice','You selected: ' + rec);

Ext.getCmp('report').load({
url: 'PDFStaticReport?action=PDFStaticReport',
params: {
'SR_ID': rec
}
});
} // if
} // function
} // preview tb btn



J2EE servlet code looks like this:


sos = response.getOutputStream();
response.setContentType("application/pdf");
response.setHeader("Content-disposition", "attachment; filename=" + staticReportBridge.getName() + ".pdf");

response.setContentLength(baosPDF.size());
baosPDF.writeTo(sos);
sos.flush();
sos.close();


The problem with this now is that I have not button to click because of the x-hidden.
I have a limited knowledge of WebDev & JS. Really appreciate the help.

Condor
15 Dec 2010, 7:34 AM
ux.report isn't a button; it's a hidden IFRAME. You have to use a separate button that calls Ext.getCmp('report').load().

(Animal's LinkButton is a real button - which has the advantage that you can right-click to use Save As).