javascript - 透過ajax +php header下載文件
为情所困
为情所困 2017-05-16 13:13:13
0
2
505

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>
        <p id="download" style="cursor: pointer;">下载</p>
</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));                                                                              //读取文件并输出文件(即下载文件) 

?>

为情所困
为情所困

全部回覆(2)
左手右手慢动作

你這應該在彈框後面使用windows.location.href="/download.php"或直接彈跳窗後面a標籤跳轉

洪涛

ajax在後台發送和接受數據,你這樣只會把數據返回到js裡面。

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!