您好,登錄后才能下訂單哦!
怎么在php中利用JavaScript實現(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);
前端頁面
在很多時候,我們下載文件的操作,都是在前端頁面直接點擊下載的,而不是專門跳轉(zhuǎn)到上面的download.php去下載。
所以我們需要在前端實現(xiàn)無刷新訪問download.php來下載文件,通過隱藏的iframe來實現(xiàn)是不錯的方式。下面是代碼:
<!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" 測試文件.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ù)代替,效率更高。
看完上述內(nèi)容是否對您有幫助呢?如果還想對相關(guān)知識有進一步的了解或閱讀更多相關(guān)文章,請關(guān)注億速云行業(yè)資訊頻道,感謝您對億速云的支持。
免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。