本文實(shí)例講述了php+js實(shí)現(xiàn)的無刷新下載文件功能。分享給大家供大家參考,具體如下:
服務(wù)器端頁面
步驟就是,設(shè)置頭文件參數(shù),然后讀入并輸出文件。下面代碼的file_get_contents可以使用fread,fclose代替。
download.php
?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);
前端頁面
在很多時(shí)候,我們下載文件的操作,都是在前端頁面直接點(diǎn)擊下載的,而不是專門跳轉(zhuǎn)到上面的download.php去下載。
所以我們需要在前端實(shí)現(xiàn)無刷新訪問download.php來下載文件,通過隱藏的iframe來實(shí)現(xiàn)是不錯(cuò)的方式。下面是代碼:
!DOCTYPE html>
html lang="en">
head>
meta charset="UTF-8">
title>Title/title>
/head>
body>
a href="javascript:download_file('http://localhost/download.php?filename=\" rel="external nofollow" 測(cè)試文件.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);
}
//alert(download_file.iframe);
download_file.iframe.src = url;
download_file.iframe.style.display = "none";
}
/script>
/body>
/html>
file_get_contents先讀取,然后echo的方式??梢允褂胷eadfile函數(shù)代替,效率更高。
更多關(guān)于PHP相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《php文件操作總結(jié)》、《PHP目錄操作技巧匯總》、《PHP常用遍歷算法與技巧總結(jié)》、《PHP數(shù)據(jù)結(jié)構(gòu)與算法教程》、《php程序設(shè)計(jì)算法總結(jié)》及《PHP網(wǎng)絡(luò)編程技巧總結(jié)》
希望本文所述對(duì)大家PHP程序設(shè)計(jì)有所幫助。
您可能感興趣的文章:- javascript使用Blob對(duì)象實(shí)現(xiàn)的下載文件操作示例
- 原生js實(shí)現(xiàn)文件上傳、下載、封裝等實(shí)例方法
- JavaScript實(shí)現(xiàn)文件下載并重命名代碼實(shí)例
- js使用文件流下載csv文件的實(shí)現(xiàn)方法
- 通過JavaScript下載文件到本地的方法(單文件)
- Jsp+Servlet實(shí)現(xiàn)文件上傳下載 刪除上傳文件(三)
- Jsp+Servlet實(shí)現(xiàn)文件上傳下載 文件列表展示(二)
- Jsp+Servlet實(shí)現(xiàn)文件上傳下載 文件上傳(一)
- JSP servlet實(shí)現(xiàn)文件上傳下載和刪除
- JavaScript實(shí)現(xiàn)多文件下載方法解析