I have an action class that generates a PDF. The contentType
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 action
through an Ajax call. I don't know the way to deliver this stream to browser. I tried a few things but nothing worked.
$.ajax({
type: "POST",
url: url,
data: wireIdList,
cache: false,
success: function(response)
{
alert('got response');
window.open(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.
create a hidden iframe, then in your ajax code above:
url:
document.getElementById('myiframeid').src = your_server_side_url
,and remove the
window.open(response);
I don't really think that any of the past answers spotted out the problem of the original poster. They all presume a GET request while the poster was trying to POST data and get a download in response.
In the course of searching for any better answer we found this jQuery Plugin for Requesting Ajax-like File Downloads.
In its "heart" it creates a "temporary" HTML form containing the given data as input fields. This form is appended to the document and posted to the desired URL. Right after that the form is removed again:
Update Mayur's answer looks pretty promising and very simple in comparison to the jQuery plug-in I referred to.
This snippet is for angular js users which will face the same problem, Note that the response file is downloaded using a programmed click event. In this case , the headers were sent by server containing filename and content/type.
Do you have to do it with Ajax? Coouldn't it be a possibility to load it in an iframe?
Here is how I got this working
Updated answer using download.js