【发布时间】:2012-08-16 07:05:11
【问题描述】:
如何允许用户下载保存在服务器上的图片?目标是让用户单击链接并获得指定的图像以开始下载。
Facebook 示例:
【问题讨论】:
标签: php javascript image file download
如何允许用户下载保存在服务器上的图片?目标是让用户单击链接并获得指定的图像以开始下载。
Facebook 示例:
【问题讨论】:
标签: php javascript image file download
链接到另一个 .php 页面,而不是图像。然后在该页面上使用 content-disposition 标头,如下所示:
<?php
// Define the name of image after downloaded
header('Content-Disposition: attachment; filename="file.jpg"');
// Read the original image file
readfile('file.jpg');
?>
从那里,您可以在 get 命令中添加图像的文件名,例如
`download.php?filename=file`
然后在文件中将其引用为:
readfile($_GET['filename'].'.jpg')
【讨论】:
readfile 之类的东西之前始终清理$_GET(上面将允许我在您的服务器上下载任何以“.jpg”结尾的文件”,可能还有其他一些工作)。也许您知道这一点,但为了简洁而省略了它,但其他人可能会照搬您的示例,并在他们的服务器中引入一个很大的安全漏洞。
您需要在提供图像的响应上设置特定标头以强制下载。
Content-Disposition: attachment; filename=myawesomefilename.png
否则它只会在浏览器中加载。
所以发送该标头,然后只需链接到带有该标头的传递该图像的路径。
【讨论】:
发送一个标头告诉浏览器像这样下载它:
header("Content-type: application/force-download")
然后将文件本身的数据发送给他们,无需任何 HTML 或任何内容。
这个例子截自PHP docs
<?php
$file = 'monkey.gif';
if (file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($file));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
ob_clean();
flush();
readfile($file);
exit;
}
?>
【讨论】:
application/force-download的媒体类型。
如果“下载保存在服务器上的图片”是指“尝试让浏览器提供“另存为”对话框而不是只显示图像”,那么您可能需要考虑使用 Content-Disposition: attachment 标头提供图像的响应:
Content-Disposition: attachment; filename="thefilename.jpg"
您可以使用header function 在php 中设置标题。
【讨论】: