[英]How can I allow users to download pictures (.gif,.png,.jpeg)?
How can I allow users to download pictures saved on the server? 如何允许用户下载保存在服务器上的图片? The goal is to have the user click on a link and have a specified image to start to download.
目的是让用户单击链接并具有指定的图像以开始下载。
Facebook example: Facebook的例子:
Make the link to another .php page, not the image. 链接到另一个.php页面,而不是图像。 Then on that page use the content-disposition header like this:
然后在该页面上使用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');
?>
From there, you can just add the filename of the image in a get command like 从那里,您可以仅在get命令中添加图像的文件名,例如
`download.php?filename=file`
then reference that in the file as: 然后在文件中引用为:
readfile($_GET['filename'].'.jpg')
You need to set a specific header on the response that delivers the image in order to force a download. 您需要在传递图像的响应上设置特定的标头,以强制下载。
Content-Disposition: attachment; filename=myawesomefilename.png
Otherwise it will just load up in browser. 否则,它将仅在浏览器中加载。
So send that header and then just link to the path that delivers that image with that header. 因此,发送该标头,然后仅链接到使用该标头提供该图像的路径。
Send a header to tell the browser to download it like this: 发送标头,告诉浏览器按如下方式下载它:
header("Content-type: application/force-download")
Then send them the data for the file itself without any HTML or anything. 然后向他们发送文件本身的数据,不带任何HTML或任何内容。
This example is snipped from the PHP docs 此示例摘自PHP文档
<?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;
}
?>
If by "download pictures saved on the server" you mean "try to make the browser offer a 'save as' dialog box instead of just displaying the image" then you might want to look into using the Content-Disposition: attachment header in the response that serves the image: 如果通过“下载保存在服务器上的图片”的意思是“尝试使浏览器提供“另存为”对话框,而不是仅显示图像”,那么您可能希望使用“ Content-Disposition:”附件标头提供图片的响应:
Content-Disposition: attachment; filename="thefilename.jpg"
You can set headers in php using the header function . 您可以使用header函数在php中设置标题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.