PHP   发布时间:2022-04-04  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了期待明天无限好:js php实现无刷新下载功能大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

js结合PHP实现下载功能

服务端

步骤就是,设置头文件参数,然后读入并输出文件。下面代码的file_get_contents可以使用fread,fclose代替。

download.PHP

1

2

3

4

5

6

7

8

<?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来实现是不错的方式。下面是代码

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

<!DOCTYPE html>

<html>

<head>

@H_731_197@  <Meta charset="UTF-8">

@H_731_197@  <title>title</title>

</head>

<body>

<a href="javascript:download_file('http://localhost/download.PHP?filename=\" rel="external nofollow" 测试文件.doc\"')">下载</a>

<script type="text/javascript">

@H_731_197@  function download_file(url)

@H_731_197@  {

@H_731_197@    if (typeof (download_file.iframE) == "undefined")

@H_731_197@    {

@H_731_197@      var iframe = document.createElement("iframe");

@H_731_197@      download_file.iframe = iframe;

@H_731_197@      document.body.appendChild(download_file.iframE);

@H_731_197@    }

@H_731_197@    //alert(download_file.iframE);

@H_731_197@    download_file.iframe.src = url;

@H_731_197@    download_file.iframe.style.display = "none";

@H_731_197@  }

</script>

</body>

</html>

file_get_contents先读取,然后echo的方式。可以使用readfile函数代替,效率更高。

以上就是js PHP实现无刷新下载功能的详细内容

大佬总结

以上是大佬教程为你收集整理的期待明天无限好:js php实现无刷新下载功能全部内容,希望文章能够帮你解决期待明天无限好:js php实现无刷新下载功能所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: