Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force Browser to download Image with Javascript window.open?

Tags:

javascript

php

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!

like image 372
Jay Wit Avatar asked Apr 13 '11 12:04

Jay Wit


People also ask

How do I trigger a download when clicking HTML button or Javascript?

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.

How do I force a file to download instead of open in browser?

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.

How do I download a file using Javascript?

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).


2 Answers

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

like image 160
Gumbo Avatar answered Oct 12 '22 23:10

Gumbo


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;     } } 
like image 30
Kaartikeyan R Avatar answered Oct 12 '22 22:10

Kaartikeyan R