Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
136 views
in Technique[技术] by (71.8m points)

通过ajax +php header下载文件

1.两个文件一个是浏览器页面,一个是后台php文件,想使用php header来下载文档,像下面这样写之后,如何在浏览器页面弹出提示下载的对话框。目前是点击浏览器窗口的下载没反应,但是如果在文档列表窗口直接点击download.php文件是可以弹出下载窗口的,想达到的效果是直接在浏览器界面点击下载会弹出下载对话框

<!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>下载中心</h2>
        <div id="download" style="cursor: pointer;">下载</div>
</body>
</html>

后台php文件:

<?php

$file = "C:file.txt"; 
$fileName = basename($file);  //获取文件名
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');//打开文件
echo fread($h, filesize($file));                                                                              //读取文件并输出文件(即下载文件) 

?>

图片描述


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

你这应该在弹框后面使用windows.location.href="/download.php"或者直接弹窗后面a标签跳转


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.6k users

...