溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

js結(jié)合php實(shí)現(xiàn)下載功能

發(fā)布時(shí)間:2020-05-12 15:54:30 來源:億速云 閱讀:236 作者:Leah 欄目:編程語言

本文在介紹關(guān)于js和php實(shí)現(xiàn)無刷新下載功能的基礎(chǔ)上,重點(diǎn)探討了其具體步驟,步驟簡(jiǎn)單易上手操作,文章內(nèi)容步步緊湊,希望大家根據(jù)這篇文章可以有所收獲。

 js結(jié)合php實(shí)現(xiàn)下載功能

js結(jié)合php實(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>
<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>

看完上述內(nèi)容,你們掌握js結(jié)合php實(shí)現(xiàn)下載功能的方法了嗎?如果還想學(xué)到更多技能或想了解更多相關(guān)內(nèi)容,歡迎關(guān)注億速云行業(yè)資訊頻道,感謝各位的閱讀!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI