本文实例讲述了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函数代替,效率更高。
更多关于PHP相关内容感兴趣的读者可查看本站专题:《php文件操作总结》、《PHP目录操作技巧汇总》、《PHP常用遍历算法与技巧总结》、《PHP数据结构与算法教程》、《php程序设计算法总结》及《PHP网络编程技巧总结》
希望本文所述对大家PHP程序设计有所帮助。
您可能感兴趣的文章:
- javascript使用Blob对象实现的下载文件操作示例
- 原生js实现文件上传、下载、封装等实例方法
- JavaScript实现文件下载并重命名代码实例
- js使用文件流下载csv文件的实现方法
- 通过JavaScript下载文件到本地的方法(单文件)
- Jsp+Servlet实现文件上传下载 删除上传文件(三)
- Jsp+Servlet实现文件上传下载 文件列表展示(二)
- Jsp+Servlet实现文件上传下载 文件上传(一)
- JSP servlet实现文件上传下载和删除
- JavaScript实现多文件下载方法解析
本文由 华域联盟 原创撰写:华域联盟 » php+js实现的无刷新下载文件功能示例
转载请保留出处和原文链接:https://www.cnhackhy.com/61717.htm