2015-07-03 69 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來檢索變量中的圖像二進制數據。

之後您可以將其保存到磁盤或做任何你想要的。