How to download a file form php with javascript?

by raven_corwin , in category: PHP General , 7 months ago

How to download a file form php with javascript?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by lottie , 7 months ago

@raven_corwin 

To download a file from PHP using JavaScript, you can use AJAX to send a request to the PHP script that generates the file and then use the Blob object to create a URL that represents the file data. Here is an example code snippet:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// Function to download file from PHP
function downloadFile() {
  // Send an AJAX request to PHP script
  var xhr = new XMLHttpRequest();
  xhr.open('GET', 'download.php', true);
  xhr.responseType = 'blob';

  xhr.onload = function() {
    if (this.status === 200) {
      // Create blob object
      var blob = new Blob([this.response], { type: 'application/octet-stream' });
      var url = URL.createObjectURL(blob);
      
      // Create a link element to download the file
      var a = document.createElement('a');
      a.href = url;
      a.download = 'file.txt';
      document.body.appendChild(a);
      a.click();
      window.URL.revokeObjectURL(url);
    }
  };

  xhr.send();
}


In the example above, the downloadFile() function sends an AJAX request to the download.php script on the server, which generates the file content. When the response is received, a Blob object is created from the response data and a URL representing the file is generated using URL.createObjectURL(). Finally, a link element is created dynamically, set to download the file on click, and then clicked programmatically to initiate the download.


Make sure to replace download.php with the actual path to your PHP script that generates the file content. Additionally, adjust the file name and type accordingly.