我想实现一个按钮,用于下载在外部服务器上传的图像。强制从外部服务器下载图像
HTML 5下载属性确实有效,但是在FireFox和IE10中,它会在新窗口中打开图像,用户仍然必须使用右键单击以将图像保存为。
<a href="https://externalserver/images/image.png" download="edited_image.png">Save</a>
我可以使用PHP强制下载,如果图像位于我的服务器。
<?php
$file = $_GET['file'];
download_file($file);
function download_file($fullPath){
// Must be fresh start
if(headers_sent())
die('Headers Sent');
// Required for some browsers
if(ini_get('zlib.output_compression'))
ini_set('zlib.output_compression', 'Off');
// File Exists?
if(file_exists($fullPath)){
// Parse Info/Get Extension
$fsize = filesize($fullPath);
$path_parts = pathinfo($fullPath);
$ext = strtolower($path_parts["extension"]);
// Determine Content Type
switch ($ext) {
case "png": $ctype="image/png"; break;
case "jpeg":
case "jpg": $ctype="image/jpg"; break;
default: $ctype="application/force-download";
}
header("Pragma: public"); // required
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false);
header("Content-Type: $ctype");
header("Content-Disposition: attachment; filename=\"".basename($fullPath)."\";");
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".$fsize);
ob_clean();
flush();
readfile($fullPath);
} else
die('File Not Found');
}
?>
HTML
<a href="/php/download.php?file=image01.jpg">Download1</a>
有没有办法避免与HTML5下载属性在FF和IE一个新窗口中打开图片的问题? -Chrome工程很棒。
有没有办法做到这一点与PHP,但当图像位于和外部服务器?
这将是很好的做任何方式,HTML 5或PHP。谢谢你的帮助。问候。
感谢您的帮助 1.从哪里得到var $ generatePath? 2.在file_get_contents中我需要通过链接发送代码的html部分中的$ file,所以它会是这样的: file_put_contents($ fullpath,file_get_contents($ fullPath));我对吗? – Diego
Fullpath是你想要的。如果你不打算缓存文件,那么使用tmpnam(),如果你打算缓存它(例如)URL的sha1。 2 - 是的 – symcbean
工程就像一个魅力。谢谢哥们。 – Diego