Nayn Nayn - 1 year ago 234
Javascript Question

Download and open pdf file using Ajax

I have an action class that generates a pdf. The

is set appropriately.

public class MyAction extends ActionSupport
public String execute() {
File report = signedPdfExporter.generateReport(xyzData, props);

inputStream = new FileInputStream(report);
contentDisposition = "attachment=\"" + report.getName() + "\"";
contentType = "application/pdf";
return SUCCESS;

I call this
through an Ajax call. I don't know the way to deliver this stream to browser. I tried a few things but nothing worked.

type: "POST",
url: url,
data: wireIdList,
cache: false,
success: function(response)
alert('got response');;
error: function (XMLHttpRequest, textStatus, errorThrown)
alert('Error occurred while opening fax template'
+ getAjaxErrorString(textStatus, errorThrown));

The above gives the error:

Your browser sent a request that this server could not understand.

Answer Source

You don't necessarily need Ajax for this. Just an <a> link is enough if you set the content-disposition to attachment in the server side code. This way the parent page will just stay open, if that was your major concern (why would you unnecessarily have chosen Ajax for this otherwise?). Besides, there is no way to handle this nicely acynchronously. PDF is not character data. It's binary data. You can't do stuff like $(element).load(). You want to use completely new request for this. For that <a href="pdfservlet/filename.pdf">pdf</a> is perfectly suitable.

To assist you more with the server side code, you'll need to tell more about the language used and post an excerpt of the code attempts.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download