Reputation: 1436
Similar to POST to server, receive PDF, deliver to user w/ jQuery But that doesn't seem to be working here...
I need to POST a request to a server, with a payload of name/value pairs. The server respondes by sending a PDF file
All the user needs to know is that, after clicking a pdf button on the page they get whatever the browser default behavior is (i.e. save or view).
So, the call is a simple one (I think)
$.ajax({
url:"http://blah.com/etc",
data:{filename:'output.pdf', foo:'foo', bar:'bar', baz:'baz'},
type:"POST"
});
That's all the server needs to do its stuff and return output.pdf
It looks like it's working fine. Here are the response headers:
Connection:keep-alive
Content-Disposition:attachment; filename="output.pdf"
Content-Length:17896
Content-Type:application/pdf
Date:Thu, 03 Oct 2013 04:19:06 GMT
Server:nginx
And, if I look at the response in Chrome dev tools, it sure looks like a 17k pdf to me...
The last hurdle though is that the browser (Chrome or FF) is doing nothing, I guess I'm missing the bit that says 'now handle this response as a downloadable file'
Upvotes: 0
Views: 5862
Reputation: 499
If you want to save/open file, you could use php alternatively. See below:
First, make a file name 'download.php' contain the following code:
$filename = $_GET['fname'];
header('Pragma: public');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Cache-Control: private', false); // required for certain browsers
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'. basename($filename) . '";');
header('Content-Transfer-Encoding: binary');
header('Content-Length: ' . filesize($filename));
readfile($filename);
$fp=fopen($filename,"rb");
if(!feof($fp)){
print(fread($fp,1024*8));
flush();
ob_flush();
if(connection_aborted){
}
}else{
echo 'File has been downloaded.';
}
exit;
Then, call your download.php:
<a href="download.php?fname=sample.pdf">Sample file</a>
This code can be used to download any file type.
P.S. Always be careful with the path and the permission issue.
Hope it's useful...
Cheers,
Upvotes: 1
Reputation: 1436
First time I've answered my own question so, here goes...
There is a JQuery forum post on this subject here http://forum.jquery.com/topic/download-file-from-jquery-post
It appears that the reason this doesn't work and never will is that these headers never reach the browser in a way that the browser can respond to - AJAX results are passed to the calling script without browser intervention.
Makes perfect sense really.
Still interested in case anyone has a better solution but, as of now, I'm generating a hidden form at runtime using JQuery and then firing off a .submit()
That's working.
Upvotes: 0