2015-07-03 72 views
0
  1. 我想实现一个按钮,用于下载在外部服务器上传的图像。强制从外部服务器下载图像

  2. 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> 
  1. 有没有办法避免与HTML5下载属性在FF和IE一个新窗口中打开图片的问题? -Chrome工程很棒。

  2. 有没有办法做到这一点与PHP,但当图像位于和外部服务器?

这将是很好的做任何方式,HTML 5或PHP。谢谢你的帮助。问候。

回答

1

将其复制到您的服务器并从那里下载。

file_put_contents($fullpath, 
    file_get_contents('https://externalserver/images/image.png'));   
header("Pragma: public"); // wtf? 
header("Expires: 0"); 
header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); 
// omg what have you been reading? 
header("Cache-Control: private",false); 
// obviously not rfc 2616 
header("Content-Type: $ctype"); 
header("Content-Disposition: attachment; filename=\"".basename($generatedPath)."\";"); 
header("Content-Transfer-Encoding: binary"); 
header("Content-Length: ".$fsize); 
ob_clean(); 
flush(); 
readfile($fullPath); 
+0

感谢您的帮助 1.从哪里得到var $ generatePath? 2.在file_get_contents中我需要通过链接发送代码的html部分中的$ file,所以它会是这样的: file_put_contents($ fullpath,file_get_contents($ fullPath));我对吗? – Diego

+0

Fullpath是你想要的。如果你不打算缓存文件,那么使用tmpnam(),如果你打算缓存它(例如)URL的sha1。 2 - 是的 – symcbean

+0

工程就像一个魅力。谢谢哥们。 – Diego

0

对于PHP部分。如果你有图像的URL,你可以使用很多方法。

一个简单的方法就是调用file_get_content来检索变量中的图像二进制数据。

之后您可以将其保存到磁盘或做任何你想要的。