Reputation: 591
I want to implement a button that downloads an image uploaded in a external server.
HTML 5 download attribute does work, but in FireFox and IE10 it opens the image in a new window and the user still have to use the right click to save image as.
<a href="https://externalserver/images/image.png" download="edited_image.png">Save</a>
I can force the download using PHP if the image is located in my server.
<?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>
Is there a way to avoid with the HTML5 download attribute the problem to open the image in a new window in FF and IE? -Chrome works great-.
Is there a way to do it with PHP but when the image is located at and external server?
It will be great to do it any way, HTML 5 or PHP. Thanks for any help. Greetings.
Upvotes: 0
Views: 3070
Reputation: 48357
Copy it to your server and download from there.
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 );
Upvotes: 1
Reputation: 996
For the php part. If you have the URL of the image you can use many approach.
An easy one would be a simple call to file_get_content to retrieve the image binary data in a variable .
After you can save it to the disk or do whatever you want with it.
Upvotes: 0