0

i want to download image on click in a href tag

i'm using download attribute in tags but not working on other server image.

example -

is working

<a href="myfolder/googlelogo_color_272x92dp.png" target="_blank" download>Download</a>

but

<a href="https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png" target="_blank" download>Download</a> 

is not working....

3 Answers3

2

First of all, you have to make 2 new files.

1 file is : link.php
Write code inside this file

<?php
echo '<a href="DownloadImage.php">Download</a>';
?>

And 2 file is: DownloadImage.php

Write code inside this (DownloadImage.php) file

<?php
$filePath = "https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png"; 

header("Content-Description: File Transfer"); 
header("Content-Type: application/octet-stream"); 
header("Content-Disposition: attachment; filename=" . basename($filePath)); 

readfile ($filePath);
exit(); 
?>

Here , inside $filePath variable set the path of the file you want to download.

I hope you will be able to download the file.

sanjay sisodiya
  • 455
  • 4
  • 14
0

Based on sanjay sisodiya's answer

1. index.html:

Our link refers to the PHP file

<a href="download.php">Download</a>

2. download.php:

Now we can set the headers to download the file

<?php
    $filePath = "https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png"; 

    header("Content-Description: File Transfer"); 
    header("Content-Type: application/octet-stream"); 
    header("Content-Disposition: attachment; filename=" . basename($filePath)); 

    readfile ($filePath);
    exit();
?>
Kriskó Tamás
  • 111
  • 1
  • 2
  • 11
  • Can you explain further why you've copied the answer of sanjay sisodiya? – Nico Haase Jun 25 '19 at 13:54
  • Because I've found a mistake in it and I can't comment below the answer. – Kriskó Tamás Jun 25 '19 at 13:56
  • And can you **explain** that mistake such that others, including the person you are copying from, can learn from it? – Nico Haase Jun 25 '19 at 14:11
  • @sanjay sisodiya missed an 'echo' from the link.php, so it resulted an error, but sorry, if I want to help you, you've definitely realized the problem without my answer. And yes, I mentioned his username. **Edit: That's true that I didn't explain the problem directly in the answer.** – Kriskó Tamás Jun 25 '19 at 14:18
0

The download works with the same origin only. If you refer an image outside (google.com) your domain it prevents the download.

dnaveen
  • 221
  • 3
  • 8