我想實現一個按鈕,用於下載在外部服務器上傳的圖像。強制從外部服務器下載圖像
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