有没有办法让图像一旦点击就下载(没有右键单击保存图像)?
我正在使用一个小的Javascript函数来调用下载页面:
<a href="#"
onclick="window.open('download.php?file=test.jpg', 'download', 'status=0');"
>Click to download</a>
Run Code Online (Sandbox Code Playgroud)
在download.php页面中我有类似的东西:
$file = $_GET['file'];
header('Content-Description: File Transfer');
header("Content-type: image/jpg");
header("Content-disposition: attachment; filename= ".$file."");
readfile($file);
Run Code Online (Sandbox Code Playgroud)
但它不起作用.我究竟做错了什么?
提前致谢!
Gum*_*mbo 23
使用application/octet-stream而不是image/jpg:
如果在具有application/octet-stream内容类型的响应中使用[Content-Disposition]标头,则隐含的建议是用户代理不应显示响应,而是直接输入"保存响应为..."对话.
- RFC 2616 - 19.5.1内容处理
小智 19
我想你忘了在标题上添加Path
if(isset($_GET['file'])){
//Please give the Path like this
$file = 'images/'.$_GET['file'];
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, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
ob_clean();
flush();
readfile($file);
exit;
}
}
Run Code Online (Sandbox Code Playgroud)
或者您可以将.htaccess文件用于所有图像文件.如果您想强制浏览器下载所有图像(从表格列表中删除):
RewriteEngine On
RewriteBase /
RewriteCond %{QUERY_STRING} ^download$
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule .(jpe?g|gif|png)$ index.php?file=noFoundFilePage [L,NC]
RewriteCond %{QUERY_STRING} ^download$
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule .(jpe?g|gif|png)$ - [L,NC,T=application/octet-stream]
Run Code Online (Sandbox Code Playgroud)
这会查找图像文件,试图强制将它们下载到浏览器中.-f RewriteConds还检查文件是否存在..最后一条规则确保下载仅用于某些文件类型.
| 归档时间: |
|
| 查看次数: |
42741 次 |
| 最近记录: |