There is a download button on the client, which, when clicked, leaves a request to the server in order to get the file for download.

Like that:

let xhr = new XMLHttpRequest(); xhr.open('POST', 'download.php'); xhr.send(JSON.stringify({ src: '/path/to/image/' })); 

We sent to the server the path to the file that we want to download, for example.

Now on the server we get the path and form the answer:

  $str_json = json_decode(file_get_contents('php://input')); $filename = dirname(__FILE__) . str_replace('/', '\\', $str_json->src); header('Content-Type: application/octet-stream'); header('Content-Disposition: attachment; filename=' . basename($filename)); header('Content-Length: ' . filesize($filename)); readfile($filename); 

In theory, with the Content-Disposition header we tell the browser how it should process the content of the message: do not display, but start downloading. But, for some reason, the download does not start, and the client from the server in the response comes the following:

PNG IHDR Ý ¡IDATxìÁA "% A ÷ @ ¯A ÷? Ì ¥ ~ b | ZéÇ ´H3ÿ ÷ ÿ · âÇ? ßßß ~}} Çq¿ßo · ¿UʪU "TV¬ PY ² @ eUʪU *" TV¨¬ .................

Ps Attribute download HTML5 is prohibited.

  • If the link is executed without ajax, but just like that, it also does not download? - teran
  • And if you add the header('Content-Transfer-Encoding: binary'); ? - Anton Shchyrov
  • @AntonShchyrov, added this header. To no avail, unfortunately. - Uladzislau Radzko
  • @teran, do you mean, just assign the link attribute to the href file path? Then the file will open in the browser. And I need to, on the server side, decide what the client needs to do with the file: view or download. - Uladzislau Radzko
  • one
    @UladzislauRadzko No. Write href="download.php?src=path_to_image" - Anton Shchyrov

0