-1

I follow what it's write here Downloading a file with a different name to the stored name . But i'm not sur too understand everything because it's don't work when i try do it with ajax. I signal that i use Smarty.

This is my html code :

 // In $attache.id their is the id of the data i want to dowload in the database
 <a href='javascript:uploadAttachFile({- $attache.id -});'><img src='../tools/telecharger.gif' /></a>

This is my jQuery code :

function uploadAttachFile(idAttache)
{
   $.ajax({
      //This permit me to go to the php function
      url: ajaxURL("attacheUpload"),
      type: "POST",
      data: {
         idAttache: idAttache
      },
      success: function(data)
      {
         alert(data);
      }
   })
}

This is my php code :

    //Permit to have the path and new title of the file
    $attacheEntite = Model_AttacheDB::getNameAndPathAttachFile(request('idAttache'));
    $file = 'path' . $attacheEntite['path'];

    if (file_exists($file))
    {
       header('Content-disposition: application/force-download; filename="' .$attacheEntite['titre']. '"');
       header("Content-Type: application/pdf");
       header('Content-Transfer-Encoding: binary');
       header("Content-Length: " . filesize($file));
       header("Pragma: ");
       header("Expires: 0");

       // upload the file to the user and quit
       ob_clean();
       flush();
       readfile($file);
       exit;
   }

I know that it pass by my php code because the ajax reuest pass by succes and alert an incomprehensible code who is certainly the code of the pdf file when i read it.

Community
  • 1
  • 1
Kvasir
  • 1,197
  • 4
  • 17
  • 31

1 Answers1

1

You can't make the client download the file through an ajax request.

What you are doing here is reading the file server-side with PHP and returning his content to the caller script ( in fact you see the content in the "data" variable )

Without ajax, you can call the script like this:

<a href='path/to/your/phpscript.php' target='_blank' ><img src='../tools/telecharger.gif' /></a>

And it will send the file to the browser

EDIT: if you add the attribute target="_blank" to the anchor it will open the download in a new tab, without reloading the current page

Moppo
  • 18,797
  • 5
  • 65
  • 64