我有一个信息列表,其中有一个字段名称是超链接的字段。我希望用户在点击它时下载该特定文件。
那么,如何使用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功能
<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>
下载链接
<a href="javascript:download('http://localhost/project/images/','DMS.doc');">DMS.doc</a>
答案 0 :(得分:6)
那么,如何使用PHP单击文件名下载文件?
最简单的方法应该是链接它。
<a href="download.php?......" target="_blank">DMS.doc</a>
答案 1 :(得分:4)
你不需要AJAX,你甚至不能用AJAX做你想做的事。如果要将URL混淆为文件,请将下载函数替换为:
function download(path,val) {
window.location.href = path+"download.php?val="+val;
};
答案 2 :(得分:-1)
// 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 {