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

2025-05-27 0 65

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

服务器端页面

步骤就是,设置头文件参数,然后读入并输出文件。下面代码的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 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程序设计有所帮助。

原文链接:https://blog.csdn.net/koastal/article/details/51879446

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 php+js实现的无刷新下载文件功能示例 https://www.kuaiidc.com/71380.html

相关文章

发表评论
暂无评论