快速发布收录 免费推广展示
下午好, 游客 <游客> [ 马上登录 | 注册帐号 ]
首页 技术交流 正文

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

时间:2022-12-24 22:41 作者: 18793网站目录导航 阅读:610 次

本文实例讲述了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" 测试文件.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函数代替,效率更高。

共收录0个网站,0个公众号,0个小程序,0个资讯文章,0个微信文章
首页 关于我们 联系我们 收录标准 广告合作 免责声明 友情链接
点击收藏小提示:按键盘CTRL+D也能收藏哦!
网站声明:本站所有资料取之于互联网,任何公司或个人参考使用本资料请自辨真伪、后果自负,不承担任何责任。在此特别感谢您对分类目录网的支持与厚爱!
版权所有©(2015-2023)18793.CC All Rights Reserved.   浙ICP备2022030117号-1