如何创建下载链接以下载文件而不是重定向到浏览器? [英] How to create download link to download a file instead of redirecting to browser?

查看:60
本文介绍了如何创建下载链接以下载文件而不是重定向到浏览器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试放置一个链接以从服务器下载pdf,而不是重定向浏览器以在另一页中打开pdf.我在许多站点中都看到过这样的选项,但无法获取代码.而且大多数人说,仅使用php应该是可能的,有人可以帮我解决这个问题.

I am trying to put a link to download a pdf from server, instead of redirecting the browser to open the pdf in another page. I have seen such options in many sites but unable to get the code. And most people says it should be possible with php only, could anyone help me for this.

推荐答案

使用以下代码将其重定向到php页面:

Redirect it to a php page with this code:

$path_to_file = '/var/www/somefile.pdf'; //Path to file you want downloaded
$file_name = "somefile.pdf"; //Name of file for download
header('Pragma: public');   // required
header('Expires: 0');    // no cache
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header("Content-Type: application/octet-stream");
header('Content-Disposition: attachment; filename="'.$file_name.'"');
header('Content-Transfer-Encoding: binary');
readfile($path_to_file);
die();

这篇关于如何创建下载链接以下载文件而不是重定向到浏览器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆