我有这个问题。在我的网站上,我想显示带链接的文件夹的内容。如果我单击此链接,我希望它将文件的源分配给另一个链接/按钮。因此,如果我点击下载按钮,它会下载我点击的文件。
这就是我要将文件显示为链接:
<?php
$path = "./files";
$dir_handle = @opendir($path) or die("Unable to open $path");
while ($file = readdir($dir_handle)) {
if($file == "." || $file == ".." || $file == "index.php" )
continue;
echo "<a href=\"".$path."/".$file."\">$file</a><br />";
}
closedir($dir_handle);
?>
所以这会创建文件夹中每个文件的链接,但我无法弄清楚如何将我点击的文件源分配到下载按钮/链接。至少我不知道如何为每个文件制作下载链接。
答案 0 :(得分:0)
试试这个并注意,这可能不起作用,具体取决于服务器和PHP设置。我假设您使用的是正确配置的Apache(或类似Apache的)服务器:
<?php
// Get the document root the server or virtual host is pointing to
$docroot = $_SERVER['DOCUMENT_ROOT'];
$docrootLen = strlen($docroot);
// realpath to get the full/expanded path to the files directly
$path = realpath('./files');
$dir_handle = @opendir($path) or die("Unable to open $path");
while ($file = readdir($dir_handle)) {
if($file == "." || $file == ".." || $file == "index.php" )
continue;
// Create fileUrl by removing $docroot from the beginning of $path
$fileUrl = substr($path, strpos($path, $docroot) + $docrootLen) . '/' . $file;
echo '<a href="' . $fileUrl . '">', $file, '</a><br />';
}
?><a id="download-button"></a><?php
closedir($dir_handle);
对于&#34;另一个链接&#34;部分,注意我在上面添加了一个额外的锚标记,其中包含ID&#34; download-button&#34;。这将是下载按钮。在HTML的末尾(在结束正文标记之前),您可以在<script>
标记内添加此脚本:
var links = document.getElementsByTagName("a"), linkIdx;
for( linkIdx in links ) {
if( links[linkIdx].getAttribute("id") == "download-button" ) {
// These are not the anchor tags you are looking for...
continue;
}
links[linkIdx].addEventListener("click", function(e){
// When the user clicks the link, don't allow the browser go to the link:
e.preventDefault();
document.getElementById("download-button").setAttribute("href", this.getAttribute("href"));
document.getElementById("download-button").innerHTML = this.innerHTML;
});
}