How to download image with ajax in php?

by filiberto , in category: PHP General , 6 months ago

How to download image with ajax in php?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by larissa , 6 months ago

@filiberto 

To download an image with Ajax in PHP, you can use a combination of client-side JavaScript and server-side PHP code. Here is a step-by-step guide:

  1. Create an HTML file with a button or link that will trigger the download. Furthermore, you will need a placeholder for the downloaded image. For example:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
<!DOCTYPE html>
<html>
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
  <button id="download-btn">Download Image</button>
  <img id="downloaded-image" src="" alt="">
  <script src="script.js"></script>
</body>
</html>


  1. Create a JavaScript file (e.g., script.js) and add the following code to handle the download event and Ajax request:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
$(document).ready(function() {
  $("#download-btn").click(function() {
    $.ajax({
      url: "download.php", // PHP server script to handle the download
      method: "GET",
      dataType: "json",
      success: function(response) {
        if (response.success) {
          $("#downloaded-image").attr("src", response.url);
        } else {
          console.log("Error downloading image.");
        }
      },
      error: function() {
        console.log("Error downloading image.");
      }
    });
  });
});


  1. Create a PHP file (e.g., download.php) to handle the Ajax request and initiate the file download. Here is an example using file_get_contents() and header() functions:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
<?php
$imageUrl = "https://example.com/path/to/image.jpg"; // Replace with the URL of the image you want to download

$filename = basename($imageUrl);
$file = file_get_contents($imageUrl);
if ($file) {
  header("Content-Type: application/octet-stream");
  header("Content-Disposition: attachment; filename=$filename");
  echo $file;
} else {
  echo json_encode(["success" => false]);
}
?>


Make sure to replace "https://example.com/path/to/image.jpg" with the actual URL of the image you want to download.

  1. Place the HTML, JavaScript, and PHP files in the same directory on your server.


When the user clicks the "Download Image" button, the JavaScript code sends an Ajax request to the PHP server script (download.php). The PHP script then fetches the image from the given URL using file_get_contents() and sets the appropriate headers to initiate the download on the client-side. Finally, the JavaScript code uses the obtained image URL to display the downloaded image in the <img> element with the id "downloaded-image".