您需要在PHP中添加什么代码,才能在访问链接时自动使浏览器将文件下载到本地计算机?
我专门考虑的功能类似于下载站点,它们会在用户单击软件名称时提示用户将文件保存到磁盘上?
在输出文件之前发送以下标头:
1 2 3 4
| header("Content-Disposition: attachment; filename="" . basename($File) .""");
header("Content-Type: application/octet-stream");
header("Content-Length:" . filesize($File));
header("Connection: close"); |
@grom:对"应用程序/八位字节流" MIME类型感兴趣。 我不知道,一直只使用'application / force-download':)
这是发送回pdf的示例。
1 2 3 4
| header('Content-type: application/pdf');
header('Content-Disposition: attachment; filename="' . basename($filename) . '"');
header('Content-Transfer-Encoding: binary');
readfile($filename); |
@Swish我没有发现应用程序/强制下载内容类型可以做任何不同的事情(在IE和Firefox中进行了测试)。 是否有没有不发回实际MIME类型的原因?
同样在PHP手册中,Hayley Watson发表:
If you wish to force a file to be downloaded and saved, instead of being rendered, remember that there is no such MIME type as"application/force-download". The correct type to use in this situation is"application/octet-stream", and using anything else is merely relying on the fact that clients are supposed to ignore unrecognised MIME types and use"application/octet-stream" instead (reference: Sections 4.1.4 and 4.5.1 of RFC 2046).
另外,根据IANA,没有注册的应用程序/强制下载类型。
一个干净的例子。
1 2 3 4 5 6 7 8 9
| <?php
header('Content-Type: application/download');
header('Content-Disposition: attachment; filename="example.txt"');
header("Content-Length:" . filesize("example.txt"));
$fp = fopen("example.txt","r");
fpassthru($fp);
fclose($fp);
?> |
我的代码适用于txt,doc,docx,pdf,ppt,pptx,jpg,png,zip扩展名,我认为最好显式使用实际的MIME类型。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| $file_name ="a.txt";
// extracting the extension:
$ext = substr($file_name, strpos($file_name,'.')+1);
header('Content-disposition: attachment; filename='.$file_name);
if(strtolower($ext) =="txt")
{
header('Content-type: text/plain'); // works for txt only
}
else
{
header('Content-type: application/'.$ext); // works for all extensions except txt
}
readfile($decrypted_file_path); |