php - 强制浏览器使用 Javascript window.open 下载图像?

标签 php javascript

有没有一种方法可以在您点击图像后将其下载(无需右键单击将图像另存为)?

我正在使用一个小的 Javascript 函数来调用下载页面:

<a href="#" 
   onclick="window.open('download.php?file=test.jpg', 'download', 'status=0');"
>Click to download</a>

在 download.php 页面中我有类似的内容:

$file = $_GET['file'];
header('Content-Description: File Transfer');
header("Content-type: image/jpg");
header("Content-disposition: attachment; filename= ".$file."");
readfile($file);

但它不起作用。我做错了什么?
提前致谢!

最佳答案

使用application/octet-stream而不是 image/jpg:

If [the Content-Disposition] header is used in a response with the application/octet-stream content-type, the implied suggestion is that the user agent should not display the response, but directly enter a `save response as...' dialog.
RFC 2616 – 19.5.1 Content-Disposition

关于php - 强制浏览器使用 Javascript window.open 下载图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5648967/

相关文章:

php - Memcached 一致性哈希不适用于 4 台服务器中的 3 台宕机

php - 这行 PHP 是否足以防止 MySQL 注入(inject)?

php - 如何记录具有大量结果的查询

javascript - 使用 jquery 动态添加删除表中的行

javascript - 在连续函数中使用 jQuery 的加载

javascript - jQuery - 将图像 src 分配给变量分配图像数据

php - MySQL 准备语句

php - Paypal 沙盒测试 - 更改 URL 端点?

javascript - 错误 [ERR_MODULE_NOT_FOUND] : Cannot find package 'express' imported from F:\Document\My Project\NODE JS\Sample 1\tinder-backend\server. js

javascript - 循环数组并返回与前 2 个值匹配的子数组的最佳方法