php 如何实现 Content-Disposition:附件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8875949/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to implement Content-Disposition: attachment?
提问by Jean Hules
I am trying to make it so that mp3's on my site are downloaded by left clicking instead of having to right click and save as, So in order to do that, I have to set the Content-Disposition: attachment. This is my first website so I am new to how to actually do this, but do I do this in my html markup or do I set this somehow with my hosting site?
我正在尝试通过左键单击下载我网站上的 mp3,而不必右键单击并另存为,因此为了做到这一点,我必须设置 Content-Disposition: 附件。这是我的第一个网站,所以我不知道如何实际执行此操作,但是我是在我的 html 标记中执行此操作还是使用我的托管站点以某种方式设置它?
Here is an example of what my markup looks like.
这是我的标记外观的示例。
<div class="download">
<a href="MP3/Morgan Page, Sultan & Ned Shepard, and BT feat. Angela McCluskey.mp3"
<img src="img/dlicon.png"/></a>
</div>
回答by Zulkhaery Basrul
Example of MP3 Lists:
MP3 列表示例:
<a href="download.php?file=testing.mp3">Download MP3</a>
<a href="download.php?file=testing2.mp3">Download MP3</a>
download.php :
下载.php :
<?php
$file = $_GET['file'];
header('Content-type: audio/mpeg');
header('Content-Disposition: attachment; filename="'.$file.'"');
?>
回答by user3468501
As others have said, you don't do that in HTML, and a dynamic solution (e.g., using PHP) is overkill.
正如其他人所说,您不会在 HTML 中这样做,并且动态解决方案(例如,使用 PHP)是多余的。
In your case, I'd configure the Content-Disposition header in the web server config. For Apache, you could set the header based on location, or have a .htaccessfile that matches certain filenames.
在您的情况下,我会在 Web 服务器配置中配置 Content-Disposition 标头。对于 Apache,您可以根据 location设置标头,或者使用与某些文件名匹配的.htaccess文件。
回答by gruentee
There's a special function for that in PHP, too:
在 PHP 中也有一个特殊的函数:
bool http_send_content_disposition ( string $filename [, bool $inline = false ] )
bool http_send_content_disposition ( string $filename [, bool $inline = false ] )
See PHP Manualhere: http://de2.php.net/manual/en/function.http-send-content-disposition.php
请参阅此处的PHP 手册:http: //de2.php.net/manual/en/function.http-send-content-disposition.php