强制文件下载 [英] forcing a file to download

查看:107
本文介绍了强制文件下载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个php页面,其中包含信息以及指向文件(例如pdf文件)的链接.文件类型可以是任何类型,因为它们可以由用户上传.

I have a php page with information, and links to files, such as pdf files. The file types can be anything, as they can be uploaded by a user.

我想知道如何强制下载任何类型的文件,而不强制下载从站点链接到其他页面的链接.我知道可以使用标头来做到这一点,但是我不想破坏网站的其余部分.

I would like to know how to force a download for any type of file, without forcing a download of links to other pages linked from the site. I know it's possible to do this with headers, but I don't want to break the rest of my site.

到其他页面的所有链接都是通过Javascript完成的,而实际的链接是指向#的链接,所以也许可以吗?

All the links to other pages are done via Javascript, and the actual link is to #, so maybe this would be OK?

我应该设置

header('Content-Disposition: attachment;)

整个页面?

推荐答案

您需要为特定资源发送以下两个标头字段:

You need to send these two header fields for the particular resources:

Content-Type: application/octet-stream
Content-Disposition: attachment

Content-Disposition可以另外具有filename参数.

您可以通过使用发送文件的PHP脚本来做到这一点:

You can do this either by using a PHP script that sends the files:

header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment');
readfile($fileToSend);
exit;

文件名通过URL传递到该脚本.或者,您可以使用某些Web服务器功能,例如 mod_rewrite 来强制键入:

And the filenames are passed to that script via URL. Or you use some web server features such as mod_rewrite to force the type:

RewriteEngine on
RewriteRule ^download/ - [L,T=application/octet-stream]

这篇关于强制文件下载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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