问题描述
我的服务器上有一个目录,我想使用复选框列出其中的所有文件,并在选择后删除或下载它们。
I have a directory on my server, I want to list all the files in it with checkboxes and either delete or download them after choosing.
到目前为止,我可以使用此表格列出并删除相关内容,勾选复选框并按按钮。但是有时我也需要将文件下载到本地计算机上。选中复选框或右键单击文件名,然后在Chrome浏览器中使用文件另存为进行下载。
So far I can list and delete fine using this form, ticking checkboxes and pressing the button. But I also sometimes need to download files to my local machine. Either by ticking the checkbox or right-clicking the file name and downloading with 'save file as' in Chrome browser. But I can't get it working.
如何下载这些文件?
How can I download these files?
我的页面称为download-ui.php
My page is called download-ui.php
<?php
if(isset($_POST['Submit']))
{
}
foreach ($_POST['select'] as $file) {
if(file_exists($file)) {
unlink($file);
}
elseif(is_dir($file)) {
rmdir($file);
}
}
$files = array();
$dir = opendir('.');
while(false != ($file = readdir($dir))) {
if(($file != ".") and ($file != "..") and ($file != "download-ui.php") and ($file != "error_log")) {
$files[] = $file;
}
}
natcasesort($files);
?>
<form id="delete" action="" method="POST">
<?php
echo '<table><tr>';
for($i=0; $i<count($files); $i++) {
if ($i%5 == 0) {
echo '</tr>';
echo '<tr>';
}
echo '<td style="width:180px">
<div class="select-all-col"><input name="select[]" type="checkbox" class="select" value="'.$files[$i].'"/>
<a href="download-ui.php?name='.$foldername."/".$files[$i].'" style="cursor: pointer;">'.$files[$i].'</a></div>
<br />
</td>';
}
echo '</table>';
?>
</table>
<br>
<button type="submit" form="delete" value="Submit">Delete File/s</button>
</form><br>
推荐答案
download-ui.php必须类似于:
The download-ui.php have to be something like:
//Only enter if there is some file to download.
if(isset($_GET['name']){
$file = basename($_GET['name']); //change if the url is absolute
if(!$file){ // file does not exist
die('file not found');
} else {
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=$file");
header("Content-Transfer-Encoding: binary");
// read the file from disk
readfile($file);
}
}
//your form
这样,您将强制下载文件。如果希望更好,可以进行AJAX调用当点击指向该网址的下载时,文件将被异步下载,例如:
This way you are forcing to download the file. If you want it better, you can make a AJAX call when click on 'download' pointing to that url, and the file will be downloaded async, like:
$.ajax({
url: 'download-ui.php',
type: 'POST',
success: function() {
window.location = 'download-ui.php';
}
});
但是如果没有AJAX,t oo。
But without AJAX will work too.
检查此内容:
希望它会有所帮助!
这篇关于PHP列表目录并删除或下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!