Is there a way to make an image a download once you click on it (without right-click save image as)?
I'm using a small Javascript function to call the download page:
<a href="#" onclick="window.open('download.php?file=test.jpg', 'download', 'status=0');" >Click to download</a>
In the download.php page I have something like:
$file = $_GET['file']; header('Content-Description: File Transfer'); header("Content-type: image/jpg"); header("Content-disposition: attachment; filename= ".$file.""); readfile($file);
But it doesn't work. What am I doing wrong?
Thanks in advance!
To trigger a file download on a button click we will use a custom function or HTML 5 download attribute. The download attribute simply uses an anchor tag to prepare the location of the file that needs to be downloaded.
Click on "Settings" and you'll see a new page pop up in your Chrome browser window. Scroll down to Advanced Settings, click Downloads, and clear your Auto Open options. Next time you download an item, it will be saved instead of opened automatically.
To ask the browser to download a file it can render, use the following header: Content-Disposition: attachment; filename="downloaded. pdf" (you can of course customize the filename as you need).
Use application/octet-stream instead of image/jpg:
If [the Content-Disposition] header is used in a response with the application/octet-stream content-type, the implied suggestion is that the user agent should not display the response, but directly enter a `save response as...' dialog.
— RFC 2616 – 19.5.1 Content-Disposition
I think you forgot to add Path on the header
if(isset($_GET['file'])){ //Please give the Path like this $file = 'images/'.$_GET['file']; if (file_exists($file)) { header('Content-Description: File Transfer'); header('Content-Type: application/octet-stream'); header('Content-Disposition: attachment; filename='.basename($file)); header('Content-Transfer-Encoding: binary'); header('Expires: 0'); header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); header('Pragma: public'); header('Content-Length: ' . filesize($file)); ob_clean(); flush(); readfile($file); exit; } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With