Dirty-flow
Dirty-flow

Reputation: 2300

forcing a download using PHP / jQuery

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.

Upvotes: 0

Views: 3896

Answers (4)

BartusZak
BartusZak

Reputation: 1253

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>'

Upvotes: 0

pregmatch
pregmatch

Reputation: 2657

  1. Return file name in ajax
  2. Do window.location.href = 'returned file name' and download will start!

Upvotes: 0

deceze
deceze

Reputation: 522513

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.

Upvotes: 1

vectorialpx
vectorialpx

Reputation: 586

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

Upvotes: 3

Related Questions