[英]Download Selected File from Directory with PHP
我有一個編寫的腳本(如下),可以正確顯示特定目錄的內容並為每個文件創建一個單選按鈕。 我希望能夠選擇一個文件並將該文件下載到我的計算機上。
是否可以通過更改表單的“操作”來實現? 還是我需要對腳本進行其他腳本或更改才能完成此任務?
<form name="myform" action="#" method="POST">
<?php
$dirPath = dir('./images');
$imgArray = array();
while (($file = $dirPath->read()) !== false)
{
if ((substr($file, -3)=="gif") || (substr($file, -3)=="jpg") || (substr($file, -3)=="png"))
{
$imgArray[ ] = trim($file);
}
}
$dirPath->close();
sort($imgArray);
$c = count($imgArray);
for($i=0; $i<$c; $i++)
{
echo "<input type=\"radio\" name=\"group1\" value=\"" . $imgArray[$i] . "\">" . $imgArray[$i] . "<br />";
}
?>
</select>
<input type="submit" value="download">
我將其放在現有腳本的開頭:
if(isset($_POST['group1'])){
$f=preg_replace('/(\.\.\/?)+/','',$_POST['group1']);
if(file_exists('./images/'.$f)){
header("Content-type: ".filetype('./images/'.$f));
header('Content-disposition: attachment; filename="'.$f.'"');
echo file_get_contents('./images/'.$f);
exit;
}
}
這是我完成Cyclone所指目標的首選方式。
header('Location: YOURFILEDOWNLOADURL; Content-type: application/force-download');
應該工作,還沒有測試。
為什么不只為目錄中的每個文件創建一個下載按鈕? 似乎無需為此使用表格。
刪除所有表單HTML並將“ for”循環更改為此,您應該可以:
foreach($imgArray as $filename)
{
echo "<a href=\"./images/$filename\">Download '$filename'</a>";
echo "<br/>";
}
(因為這使用了foreach,所以您也可以刪除將$ c設置為count($ imgArray)的行)。
如果您堅持使用表格,建議您:
將表單發送到解析腳本,該腳本讀取選定的文件,然后將用戶轉發到該文件,如Cyclone所建議的那樣,或者
按下“提交”按鈕后,使用JavaScript將頁面直接轉發到所選圖像。
但是,對於您要完成的任務,這兩種解決方案都不必要地復雜。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.