Home  >  Article  >  Backend Development  >  js php implements refresh-free download function

js php implements refresh-free download function

Guanhui
GuanhuiOriginal
2020-05-02 17:52:552739browse

js php implements refresh-free download function

js combined with php to implement the download function

Server

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

download.php

<?php
$filename = $_GET[&#39;filename&#39;];
$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);

Client

In many cases, we download files by clicking directly on the front-end page Download, rather than specifically jumping to the download.php above to download.

So we need to implement refresh-free access to download.php on the front end to download files. It is a good way to achieve this through a hidden iframe. The following is the code:

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>
<a href="javascript:download_file(&#39;http://localhost/download.php?filename=\" rel="external nofollow" 测试文件.doc\"&#39;)">下载</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 is read first and then echoed. You can use the readfile function instead, which is more efficient.

The above is the detailed content of js php implements refresh-free download function. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn