js php實現(xiàn)無刷新下載功能
來源:涼官灰
發(fā)布時間:2020-05-06 13:32:59
閱讀量:1224
js結(jié)合php實現(xiàn)下載功能
服務(wù)端
步驟就是,設(shè)置頭文件參數(shù),然后讀入并輸出文件。下面代碼的file_get_contents可以使用fread,fclose代替。
download.php
1 2 3 4 5 6 7 8 | <?php
$filename = $_GET['filename'];
$path = __DIR__."/file/".$filename;
header( "Content-type: application/octet-stream");
header( "Accept-Ranges: bytes ");
header( "Accept-Length: " .filesize($filename));
header( "Content-Disposition: attachment; filename={$filename}");
echo file_get_contents($filename);
|
客戶端
在很多時候,我們下載文件的操作,都是在前端頁面直接點擊下載的,而不是專門跳轉(zhuǎn)到上面的download.php去下載。
所以我們需要在前端實現(xiàn)無刷新訪問download.php來下載文件,通過隱藏的iframe來實現(xiàn)是不錯的方式。下面是代碼:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | <!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<a href="javascript:download_file('http://localhost/download.php?filename=\" rel="external nofollow" 測試文件.doc\"')">下載</a>
<script type="text/javascript">
function download_file(url)
{
if (typeof (download_file.iframe) == "undefined")
{
var iframe = document.createElement("iframe");
download_file.iframe = iframe;
document.body.appendChild(download_file.iframe);
}
download_file.iframe.src = url;
download_file.iframe.style.display = "none";
}
</script>
</body>
</html>
|
file_get_contents先讀取,然后echo的方式??梢允褂胷eadfile函數(shù)代替,效率更高。