php - 如何使用 PHP 单击文件名下载文件?

标签 php javascript ajax

我有一个信息列表,其中有一个文件名超链接的字段。我希望用户在点击该文件时下载该文件。

那么,如何使用PHP点击文件名下载文件呢?

我尝试使用 ajax,其代码如下,但我没有下载任何文件。

download.php

$filename = $_GET['val'];
         // Fetch the file info.
 $filePath = $_SERVER['DOCUMENT_ROOT'] . "/dfms/images/docs/".$filename;

    if(file_exists($filePath)) {
        $fileName = basename($filePath);
        $fileSize = filesize($filePath);

        // Output headers.
        header("Cache-Control: private");
        header("Content-Type: application/stream");
        header("Content-Length: ".$fileSize);
        header("Content-Disposition: attachment; filename=".$fileName);

        // Output file.
        readfile ($filePath);                   
        exit();
    }
    else {
        die('The provided file path is not valid.');
    }

javascript function

<script>
function Inint_AJAX() {
try { return new ActiveXObject("Msxml2.XMLHTTP");  } catch(e) {} //IE
try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch(e) {} //IE
try { return new XMLHttpRequest();          } catch(e) {} //Native Javascript
alert("XMLHttpRequest not supported");
return null;
};
function download(path,val) {
var req = Inint_AJAX();
req.open("GET", path+"download.php?val="+val); //make connection
//req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=iso-8859-1"); // set Header
req.send(null); //send value
req.onreadystatechange = function () {
 if (req.readyState==4) {
      if (req.status==200) {

      }
 }
};

}
</script>

link to download

<a href="javascript:download('http://localhost/project/images/','DMS.doc');">DMS.doc</a>

最佳答案

so, How to download a file on clicking the name of file using PHP?

最简单的方法应该是链接到它。

<a href="download.php?......" target="_blank">DMS.doc</a>

关于php - 如何使用 PHP 单击文件名下载文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4518702/

相关文章:

javascript - 动态生成文本区域(JQuery)以适应初始内容大小

php - 如何让 mod_rewrite 与 EasyPHP 一起工作?

php - 如何从mysql中选择一篇文章及其评论?

javascript - 帮助从pivotaltracker的javascript中学习,寻找高层次的故障

javascript - .Click() 函数不工作 Jquery

javascript - 如何仅在javascript函数内运行代码?

javascript - 数据未返回 Ajax

javascript - 服务器和客户端之间的响应方法出现 Node js错误

php - 在同一行插入更多值

php - 安全 header 无效 - 1002