Download file via ajax +php header
为情所困
为情所困 2017-05-16 13:13:13
0
2
556

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>

为情所困
为情所困

reply all(2)
左手右手慢动作

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

洪涛

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template