0

I know there are already many questions about forcing a download with PHP, but I can't find what I'm doing wrong and what should I do.

I'm having an list with filenames, and I want to download one of them by clicking a button.

My jQuery:

$(".MappeDownload").on("click",function(e){
            e.stopPropagation();
            fileId=$(this).val()
            $.post("ajax/DownloadFile.php",{ id : fileId})
})

and on the server side I have a table with the file names and the file path.

$sql = "SELECT vUploadPfad, vUploadOriginname  FROM tabUpload WHERE zUploadId='$_POST[id]'";
$result =  mysql_query($sql) or die("");
$file = mysql_fetch_array($result);
$localfile = $file["vUploadPfad"];
$name=$file["vUploadOriginname"];
$fp = fopen($localfile, 'rb');
        header("Cache-Control: ");   
        header("Pragma: ");         
        header("Content-Type: application/octet-stream");
        header("Content-Length: " . filesize($localfile));
        header("Content-Disposition: attachment; filename='".$name."';");
        header("Content-Transfer-Encoding: binary\n");
        fpassthru($fp);
        exit;

The AJAX request is successful, I'm getting the right header(filesize, filename etc...) but the download are not starting.

Dirty-flow
  • 2,306
  • 11
  • 30
  • 49
  • try hard coding a filename instead of $name, i had previous issues with this and it may be the same? – CR41G14 Dec 04 '12 at 10:58

4 Answers4

3

You don't need ajax, just redirect to the address that forces the download. The page will not change so, instead of $.post("ajax/DownloadFile.php",{ id : fileId}) you should have location.href = "ajax/DownloadFile.php?id="+fileId and, in your PHP file, convert your $_POST to $_GET

vectorialpx
  • 587
  • 2
  • 17
1

The response to an AJAX request will never trigger a download. AJAX requests are silently handled in the background, they never trigger visible activity directly.

You need to redirect the main page or an iframe to trigger the download.

deceze
  • 510,633
  • 85
  • 743
  • 889
0
  1. Return file name in ajax
  2. Do window.location.href = 'returned file name' and download will start!
pregmatch
  • 2,629
  • 6
  • 31
  • 68
0

There is my solution:

<script>
//downloading the file

 $(document).on('click', '.download_file', function(){
  var path = $(this).data("name");
  var action = "download_file"

    $.ajax({
        url: "action.php",
        method: "POST",
        data: {path:path, action:action},
        success: function(data)
        {
            window.location.href = path;
        }
      })
})
</script>

And the action.php

<button  type"button" name="download" data-name="'.$name.'" class="download_file btn btn-success btn-xs">Pobierz</button></td>'
BartusZak
  • 1,041
  • 14
  • 21