9

My question is similar to Download and open pdf file using Ajax

But not exactly the same , the reason I want an JQuery ajax is that my file is being generated dynamically from the data which would be fetched from the same page.

So basically I have a Json Object which needs to be sent to the server which would dynamically generate a file and send it back to the browser.

I would not like to use query strings on an anchor with my Json object stringyfied , as I think it would be a potential threat as query strings have character restrictions ( am I right here ?).

Please let me know If my workflow is right or I can achieve the same thing thing using a different flow.

Community
  • 1
  • 1
Nikshep
  • 2,117
  • 4
  • 21
  • 30

3 Answers3

8

You should not use AJAX to download files. This doesn't work. This being said you are left with 2 options:

  1. action link and query string parameters or if the download must be trigerred at some specific javascript event you could also set the window.location.href to the action that is supposed to generate the PDF file and pass query string parameters to it.

  2. or if you are afraid that you have lots of data to pass to the controller action that will generate the PDF to download you use a <form> with method="POST" and inside you use hidden fields to store as much parameters and data as you like:

    @using (Html.BeginForm("download", "home"))
    {
        ... hidden fields containing values that need to be sent to the server
        <input type="submit" value="Download PDF" />
    }
    
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • Darin: what do you think about generating the file on the server with an AJAX GET request? This allows me to catch any error that happens on the server during file generation in the fail callback and show it to the user. If success, I then pass the filename in the ajax success callback and do `window.location = server\folder\filename`. I'm working with ASP.NET Web API here. – Leniel Maccaferri Oct 28 '13 at 17:25
  • OP specifically asked for ajax. This is a waste of bandwidth. – CodeWarrior Feb 07 '14 at 14:02
  • @OmarPadilla, you cannot download files using AJAX to the client. But even if that was possible you would have wasted exactly the same quantity of bandwidth as if you used a direct link to download the file. The simple reason for that is that in both cases you are calling the same endpoint on the server which is returning the same file. And don't be fooled into thinking that if you don't use AJAX, the current page will *reload*. There are no additional requests other than the one to the controller action that will stream the file. – Darin Dimitrov Feb 07 '14 at 14:04
  • why shouldn't I use ajax to download files? https://dev.to/nombrekeff/download-file-from-blob-21ho – Alex78191 Mar 15 '22 at 06:09
0

Instead of making one more ajax call in your page you can use anchor tag and php force download to perform pdf download

HTML
    <a href="www.example.com/download_file.php?file_source=example.pdf">Download pdf here</a>

PHP
<?php
$fullPath = $_GET['fileSource'];
if($fullPath) {
    $fsize = filesize($fullPath);
    $path_parts = pathinfo($fullPath);
    $ext = strtolower($path_parts["extension"]);
    switch ($ext) {
        case "pdf":
        header("Content-Disposition: attachment; filename=\"".$path_parts["basename"]."\""); // use 'attachment' to force a download
        header("Content-type: application/pdf"); // add here more headers for diff. extensions
        break;
        default;
        header("Content-type: application/octet-stream");
        header("Content-Disposition: filename=\"".$path_parts["basename"]."\"");
    }
    if($fsize) {//checking if file size exist
      header("Content-length: $fsize");
    }
    readfile($fullPath);
    exit;
}
?>

I am checking for file size because if you load pdf from CDN cloudfront, you won`t get the size of document which forces the document to download in 0kb, To avoid this i am checking with this condition

  if($fsize) {//checking if file size exist
      header("Content-length: $fsize");
    }

I too was struggling with this problem, above code worked for me I hope it helps

Hitesh
  • 4,098
  • 11
  • 44
  • 82
0

I have a very sure answer. You can't download PDF file while using the ajax request to server. So instead of that you should use html actionlink. for example

@Html.ActionLink("Convert Data into PDF", "PDFView", null, new { @class= "btn btn-info" });

Above code will generate a link button and you can access Action Method of controller. Also you can use any technique to return PDF file from controller for example you can return PDF file using FileResult class.

RohannG
  • 669
  • 7
  • 12