Example of downloading files without refresh implemented by php+js

  • 2021-12-19 06:25:19
  • OfStack

In this paper, an example is given to describe the function of downloading files without refresh realized by php+js. Share it for your reference, as follows:

Server-side page

The step is to set the header file parameters, and then read in and output the file. file_get_contents of the following code can be replaced by fread, fclose.

download.php


<?php
$filename = $_GET['filename'];
$path = __DIR__."/file/".$filename;
Header( "Content-type: application/octet-stream");
Header( "Accept-Ranges: bytes ");
Header( "Accept-Length: " .filesize($filename));
header( "Content-Disposition: attachment; filename={$filename}");
echo file_get_contents($filename);

Front-end page

In many cases, we download files directly by clicking on the front page, instead of jumping to the above download. php to download.

Therefore, we need to access download. php without refreshing in the front end to download files, and it is a good way to realize it through hidden iframe. Here's the code:


<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>
<a href="javascript:download_file('http://localhost/download.php?filename=\" rel="external nofollow"  Test file .doc\"')"> Download </a>
<script type="text/javascript">
  function download_file(url)
  {
    if (typeof (download_file.iframe) == "undefined")
    {
      var iframe = document.createElement("iframe");
      download_file.iframe = iframe;
      document.body.appendChild(download_file.iframe);
    }
    //alert(download_file.iframe);
    download_file.iframe.src = url;
    download_file.iframe.style.display = "none";
  }
</script>
</body>
</html>

file_get_contents read first, then echo. readfile function can be used instead, which is more efficient.

More readers interested in PHP can check the topics of this site: "php File Operation Summary", "PHP Directory Operation Skills Summary", "PHP Common Traversal Algorithms and Skills Summary", "PHP Data Structure and Algorithm Tutorial", "php Programming Algorithm Summary" and "PHP Network Programming Skills Summary"

I hope this article is helpful to everyone's PHP programming.


Related articles: