search

Home  >  Q&A  >  body text

Download file via ajax +php header

1. One of the two files is the browser page, and the other is the background php file. I want to use the php header to download the document. After writing as follows, how can I pop up a dialog box prompting for download on the browser page? Currently, there is no response when clicking download in the browser window, but if you directly click the download.php file in the document list window, the download window will pop up. The desired effect is that clicking download directly on the browser interface will pop up the download dialog box

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>PHP download file</title>
    <style type="text/css">
        
    </style>
    <script type="text/javascript" src="jquery.js"></script>
    <script type="text/javascript">
        $(document).ready(function(e){
            $("#download").click(function(){
                // alert();
             $.ajax({
                type:"POST",
                url:"download.php",
             });
            });
        });

        
    </script>
</head>
<body>
   
        <h2>Download Center</h2>
        <p id="download" style="cursor: pointer;">Download</p>
</body>
</html>

Backend php file:

<?php

$file = "C:\file.txt";
$fileName = basename($file); //Get the file name
header("Content-Type:application/octet-stream");
header("Content-Disposition:attachment;filename=".$fileName);
header("Accept-ranges:bytes");
header("Accept-Length:".filesize($file));
$h = fopen($file, 'r');//Open the file
echo fread($h, filesize($file)); //Read the file and output the file (i.e. download the file)

?>

< /p>

为情所困为情所困2835 days ago590

reply all(2)I'll reply

  • ringa_lee

    ringa_lee2017-05-16 13:15:13

    You should use windows.location.href="/download.php" behind the pop-up window or directly jump to the a tag behind the pop-up window

    reply
    0
  • PHP中文网

    PHP中文网2017-05-16 13:15:13

    ajax sends and receives data in the background, you will only return the data to js.

    reply
    0
  • Cancelreply