是否有任何HTML技巧可以强制浏览器在用户单击链接时提供下载对话框?
非常感谢您的任何帮助或指针。
<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>
<a download="image.jpg" href="http://www.domain.com/image.jpg">Download</a>
仅使用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();
}
如果您想显示下载对话框,您需要将特殊标头添加到您的图像中
在PHP中,它将是:
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=image.jpg');
header('Content-Transfer-Encoding: binary');
AddType application/octet-stream .jpg