基本问题是:我有一个图像文件的链接。单击链接时所需的行为是获取下载对话框,这将允许我启动相关的图像编辑器。这不会发生,因为图像文件是由浏览器呈现的。
当用户点击链接时,是否有任何html魔法可用于强制浏览器提供下载对话框?
非常感谢任何帮助或指示。
答案 0 :(得分:3)
两种方法:
在锚标记的href
中使用Data URIs:
<a href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABIAAAAPCAYAAADphp8SAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAAOnAAADpwBB5RT3QAAABZ0RVh0Q3JlYXRpb24gVGltZQAwMi8yNS8xMapAVMwAAAAcdEVYdFNvZnR3YXJlAEFkb2JlIEZpcmV3b3JrcyBDUzVxteM2AAABjklEQVQ4jZWTwWoTURSGv5lMp1OmxUIUXISCCbW06daNtGuh7uMbCHaeoOBSzBMEN92LXXThohVtoAshOyuKJQkaXWRjKi7aBjPT9v6uEsbpTGp/OHDPvf/5zjmLa0niCo0zWMODA2BZVqZTEkG1RdwhoLaxMKqTBJKWJO1JOpN0Iek8EQqeNxVXLP8jqS7pniXpe+1V9+yw058ft19yoqHKJb+9XikcOcDcYadvj4Mki+P68q1/F5hz4s1qGwsABNUWszMOD+7nWS75THk5wshw0DzhbeM3x/3zJG/CiWdBtTU6r63kuZ2f5NnmD8LI4Lk2TyoFHq7mefnm56XJMldaLE5T2+oSRgaAQWR4sdWlXJpO9WeCbvi5EWSoQWSYmkwvyQRdGOG5/z57rn0JfiWo8emY4FFhBPNcm/VKgQ/Nk1S/k3oLvN4/Ym31Jk8f38FzbQah4fPXU3be/8oEGSCXfBhEhu16j+16L6tXXKENfFwq+u3/caepXPLbwDsk3ZK0G/tr14lTSTuSin8BUMr8td343bwAAAAASUVORK5CYII=">Download</a>
在某些特定的浏览器中,例如Google Chrome和Firefox,您可以这样做:
<a download="image.jpg" href="http://www.domain.com/image.jpg">Download</a>
答案 1 :(得分:0)
仅使用HTML是不可能的,但您可以通过使用服务器端语言(如PHP)修改标题来强制下载文件。
// grab the requested file's name
$file_name = $_GET['file'];
// make sure it's a file before doing anything!
if(is_file($file_name))
{
/*
Do any processing you'd like here:
1. Increment a counter
2. Do something with the DB
3. Check user permissions
4. Anything you want!
*/
// required for IE
if(ini_get('zlib.output_compression')) { ini_set('zlib.output_compression', 'Off'); }
// get the file mime type using the file extension
switch(strtolower(substr(strrchr($file_name,'.'),1)))
{
case 'pdf': $mime = 'application/pdf'; break;
case 'zip': $mime = 'application/zip'; break;
case 'jpeg':
case 'jpg': $mime = 'image/jpg'; break;
default: $mime = 'application/force-download';
}
header('Pragma: public'); // required
header('Expires: 0'); // no cache
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Last-Modified: '.gmdate ('D, d M Y H:i:s', filemtime ($file_name)).' GMT');
header('Cache-Control: private',false);
header('Content-Type: '.$mime);
header('Content-Disposition: attachment; filename="'.basename($file_name).'"');
header('Content-Transfer-Encoding: binary');
header('Content-Length: '.filesize($file_name)); // provide file size
header('Connection: close');
readfile($file_name); // push it out
exit();
}
答案 2 :(得分:0)
如果要显示下载对话框,则需要为图像添加特殊标题
PHP中的将是:
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=image.jpg');
header('Content-Transfer-Encoding: binary');
答案 3 :(得分:-1)
另一种解决方案是将其添加到包含图像的文件夹中的htaccess文件中:
AddType application/octet-stream .jpg