php+js实现的无刷新下载文件功能示例

2022-04-14 0 815

本文实例讲述了php+js实现的无刷新下载文件功能。分享给大家供大家参考,具体如下:

服务器端页面

步骤就是,设置头文件参数,然后读入并输出文件。下面代码的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);

前端页面

在很多时候,我们下载文件的操作,都是在前端页面直接点击下载的,而不是专门跳转到上面的download.php去下载。

所以我们需要在前端实现无刷新访问download.php来下载文件,通过隐藏的iframe来实现是不错的方式。下面是代码:

<!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"  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的方式。可以使用readfile函数代替,效率更高。

更多关于PHP相关内容感兴趣的读者可查看本站专题

免责声明:
1、本网站所有发布的源码、软件和资料均为收集各大资源网站整理而来;仅限用于学习和研究目的,您必须在下载后的24个小时之内,从您的电脑中彻底删除上述内容。 不得使用于非法商业用途,不得违反国家法律。否则后果自负!

2、本站信息来自网络,版权争议与本站无关。一切关于该资源商业行为与www.niceym.com无关。
如果您喜欢该程序,请支持正版源码、软件,购买注册,得到更好的正版服务。
如有侵犯你版权的,请邮件与我们联系处理(邮箱:skknet@qq.com),本站将立即改正。

NICE源码网 PHP编程 php+js实现的无刷新下载文件功能示例 https://www.niceym.com/12276.html