简体   繁体   中英

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.

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

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM