js结合php实现下载功能

服务端

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

更多相关文章

  1. php文件锁产生的问题和解决方案(一个真实案例)
  2. PHP如何删除一个路径下的所有文件夹和文件?
  3. PHP魔术方法之__call和__callStatic详解(代码实例)
  4. PHP面向对象之3种数据访问方式详解(代码实例)
  5. PHP魔术方法之__get,__set详解(代码实例)
  6. PHP中正则表达式详解(代码实例)
  7. PHP中面向对象之Final关键字详解(代码实例)
  8. PHP中面向对象之Static关键字详解(代码实例)
  9. PHP魔术方法之__iset,__unset详解(代码实例)

随机推荐

  1. 当我们走出三本的大门,现实给我们上了一课
  2. Android网络请求框架AsyncHttpClient (an
  3. 动画:面试官问我插入排序和冒泡排序哪个更
  4. COVID-19每日数据|04-06
  5. COVID-19每日数据|04-08
  6. Android: 八种燃爆了的菜单效果
  7. 超好看的弦图,Python一行代码就能做
  8. 不就是用Python做个动态图吗?看招
  9. 动画:用动画技巧记忆常见笔试 JS 类型转换
  10. 1024 小鹿自费给读者送书啦!